Calling variable to subclass from superclass - java

I'm having no luck calling a variable from my superclass to my subclass. Can anyone help out?
//SUPERCLASS
public class Circle {
protected double radius;
protected double area;
//Some code to construct object and initialize radius
//Return Calculated Area
protected double getArea() {
area = Math.pow(radius, 2) * Math.PI;
return area;
}
}
//SUBCLASS
public class Cone extends Circle {
private double height;
//Some more code with constructors and different methods
public double getVolume() {
{
return (area * height / 3)
}
}
There is a lot more to the code but the main problem I'm having is within the subclass, the 'area' variable is 0.00 and I'm unsure how to get it equal to the 'area' that is calculated in the superclass

try:
public double getVolume() {
return (getArea() * height / 3)
}
Besides: A circle should be initialized with its radius in the constructor and not have a field area, because it is dependent on the radius:
public class Circle {
protected final double radius;
public Circle(double radius) {
this.radius = radius
}
public double getArea() {
return Math.pow(radius, 2) * Math.PI;
}
}
And a cone is not a proper sub class of a circle, the cone should have a field Circle baseShape.

Here variable area is an instance variable so it's default value is set to 0.0d. Refer to this link. If you want to change the area value then want to call
getArea() method. Check below code,
public double getVolume() {
return (getArea()* height / 3)
}

Add Constructors for both super class and sub-class like the following.
//Super Class
public class Circle {
protected double radius;
protected double area;
public Circle(double radius) {
this.radius = radius;
this.area = getArea();
}
protected double getArea() {
area = Math.pow(radius, 2) * Math.PI;
return area;
}
}
//Sub Class
public class Cone extends Circle {
private double height;
public Cone(double radius, double height) {
super(radius);
this.height = height;
}
public double getVolume() {
{
return (area * height / 3);
}
}
}
After that, you can use getVolume() method of sub-class.
public class Test {
public static void main(String[] args) {
Cone c = new Cone(3.0,5.0);
System.out.println(c.getVolume());
}
}

You are using protected its totally fine to inherit the variable to subclass . here is the correct answer
//SUPERCLASS
public class Circle {
protected double radius;
protected double area;
//Some code to construct object and initialize radius
//Return Calculated Area
protected double getArea() {
area = Math.pow(radius, 2) * Math.PI;
return area;
}
}
//SUBCLASS
public class Cone extends Circle {
private double height;
//Some more code with constructors and different methods
public double getVolume() {
{
return (getArea() * height / 3)
}
}

Unless you set the value to radius and area, it remains 0. I assume you've set the value. You should use this keyword to get the set value. It would be easy to find the flaw if you put the entire code and not just hiding it as a comment.

Related

calling methods of subclass

I'm trying to learn inheritance. I have a superclass called Shape with getColor and getFilled methods. I then have 3 subclasses called Triangle, Rectangle and Circle. In each of the subclasses I have methods getPerimeter and getArea. Each shape has a subclass that extends the superclass. I then create an ArrayList and add a Triangle, Rectangle and Circle. I can call the getColor and getFilled superclass methods but run into a problem when trying to call the getPerimeter and getArea method that are created in the subclass. I think I have a misunderstanding of subclass and superclass. Here is my code:
Shape superclass
public class Shape
{
// instance variables
public String color; // color of shape
public boolean filled; // shape fill status
public Shape()
{
// initialize instance variables
color = "";
filled = false;
}
public String getColor()
{
return color;
}
public boolean getFilled()
{
return filled;
}
public String toString()
{
return getClass().getName();
}
}
Triangle (did not include here the Circle/Rectangle because they are basically the same as triangle)
public class Triangle extends Shape
{
// instance variables
private double side1;
private double side2;
private double side3;
public Triangle(String color, boolean filled, double side1, double side2, double side3)
{
// initialize instance variables
super.color = color;
super.filled = filled;
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
public double getPerimeter() {
return this.side1 + this.side2 + this.side3;
}
public double getArea() {
return (this.side2 / 2.0) * this.side1;
}
}
Tester:
import java.util.ArrayList;
public class Tester
{
public static void main(String arg[])
{
ArrayList<Shape> shapes = new ArrayList<>(); // create new array list of shapes
shapes.add(new Triangle("white", true, 3.0, 2.5, 2.0)); // Add new triangle to shapes list
shapes.add(new Rectangle("red", true, 2.0, 4.0)); // Add new rectangle to shapes list
shapes.add(new Circle("yellow", false, 1.0)); // Add new circle to shapes list
System.out.println("Starting shapes\n");
for (Shape shape: shapes) // loop through shapes
{
System.out.println(shape.toString()
+"[color="+shape.getColor()+", filled="+shape.getFilled()+"]"
); // print out string of shape/color/fill
System.out.println("Perimeter: "+shape.getPerimeter()); // print out perimeter
System.out.println("Area: "+shape.getArea()); // print out perimeter
System.out.println();
}
}
}
I expected to be able to call shape.getPerimeter() and shape.getArea() from the subclasses.
Added getPerimeter() and getArea() to parent Shape class, then added #Override in front of public class getPerimeter( and public class getArea( in all of the subclasses. Solved

How to inherit a method in Java from an A class to a C class

I have three classes. Class A is titled Circle. Class B is titled ColorfulCircle. Class C is titled ColorfulBouncingCircle. I need to inherit the methods public double getCenterY(), public double getCenterX, and public void setCenterCoordinates(double centerX, double centerY) from Class “A” Circle so that I can use them in Class “C” ColorfulBouncingCircle.
Circle looks like this:
class Circle {
private double centerX, centerY;
public double getCenterX() {
return centerX;
}
public double getCenterY() {
return centerY;
}
public void setCenterCoordinates(double centerX, double centerY) {
this.centerX = centerX;
this.centerY = centerY;
}
}
There are the exact methods I need to be able to use in ColorfulBouncingCircle so that I can use the centerX and centerY variables in code over there.
I just need to know exactly what do I type in to the ColorfulBouncingCircle class so that I can use them.
Thank you.
Extend the Circle class from ColorfulBouncingCircle class.
public class ColorfulBouncingCircle extends Circle {
}
You can then call getCenterX(), getCenterY() and setCenterCoordinates() from the object of ColorfulBouncingCircle class.

Work Around For Accessing Field of Abstract Class in Subclass

I realize this question is a duplicate many times over, but here goes:
I've been tasked for homework to create (using Java) an abstract class called Triangle that has abstract methods getArea() and getPerimeter() and a constructor which takes in a double representing the side length (you'll see why it's only one value in a second). I'm supposed to create concrete subclasses EquilateralTriangle and RightTriangle that extend Triangle and respectively implement getArea() and getPerimeter(), and they are also meant to have constructors which take in a double for the side length.
The problem I've run into is not knowing how to store the side length, given that it's meant to be stored in the field belonging to Triangle, the superclass of each subclass which needs to access that field in its own area and perimeter methods. I started out thinking I could keep it as a private field in Triangle, and that it would simply be inherited in each subclass and set correctly in each subclass' constructor via calls to super(). The compiler complained about the field having private access in Triangle, so I switched the field to protected, and it now compiles but gives me the run-time error "java.lang.IllegalAccessError: tried to access field Triangle.side from class EquilateralTriangle." I'm not sure how to go about designing this in a way that doesn't involve explicitly creating a field to hold side length in each of the subclasses, or something like that. Here's my current code:
public abstract class Triangle {
protected double side;
public abstract double getArea();
public abstract double getPerimeter();
public double getRatio() {
return getArea() / getPerimeter();
}
public Triangle(double side) {
this.side = side;
}
#Override
public String toString() {
return "Triangle: SideLen = " + this.side
+ " || Area = " + getArea()
+ " || Perimeter = " + getPerimeter()
+ " || Ratio = " + getRatio();
}
}
public class EquilateralTriangle extends Triangle {
private static final double AREA_COEFFICIENT = Math.sqrt(3) / 4;
public EquilateralTriangle(double side) {
super(side);
}
public double getArea() {
return AREA_COEFFICIENT * this.side * this.side;
}
public double getPerimeter() {
return this.side * 3;
}
}
public class RightTriangle extends Triangle {
private static final double PERIMETER_COEFFICIENT = Math.sqrt(2) + 2;
public double getArea() {
return this.side * this.side / 2;
}
public double getPerimeter() {
return this.side * PERIMETER_COEFFICIENT;
}
public RightTriangle(double side) {
super(side);
}
}
So the approach of using a protected field is fine. It may be better to make it private and then add a protected double getSide() in the Triange class.
public static abstract class Triangle {
private double side;
public abstract double getArea();
public abstract double getPerimeter();
public double getRatio() {
return getArea() / getPerimeter();
}
public Triangle(double side) {
this.side = side;
}
protected double getSide()
{
return this.side;
}
#Override
public String toString() {
return "Triangle: SideLen = " + this.side
+ " || Area = " + getArea()
+ " || Perimeter = " + getPerimeter()
+ " || Ratio = " + getRatio();
}
}
In the subclasses, replaced this.side with getSide().

How to use circle.java to calculate getVolume of a cylinder. [2 classes]

edit2
Sorry never mind I just added
public double cylinderSurfaceArea() {
return 2 * base.circleArea() + base.circleCirumference() * 2 * height;
}
}
With no error codes. This would be correct?
edit:
Thank you to all those who have answered. I have since changed my previous Cylinder class to read. Now I want to take it a step further and add
public double cylinderSurfaceArea() {
return 2 * Math.PI * radius * radius + 2 * Math.PI * radius * h;
}
However it now says that radius (or even r) returns an error "cannot find symbol - variable radius). Shouldn't the symbol be found/declared from the Circle class?
What I am trying to do is calculate the volume of a cylinder using a separate Circle.java class.
So for instance, I have the following so far for my circle.java
public class Circle {
public double radius;
public Circle(double r) {
radius = r;
}
public double circleArea() {
return Math.PI * radius * radius;
}
public double circleCirumference() {
return Math.PI * 2 * radius;
}
}
Now here are where the questions start. When making the Cylinder class do I start with:
public class Cylinder extends Circle {
If so, overall I have:
public class Cylinder extends Circle {
public Circle base;
public double height;
public Cylinder(double r, double h) {
height = h;
base = new Circle(r);
}
public double getVolume() {
return base.circleArea * height;
}
}
However, I keep getting an error after:
public Cylinder(double r, double h) {
Stating that:
constructor Circle in class Circle cannot be applied to given types; required:double; found: noarguments; reason:actual and formal arguments lists differ in length."
Can someone push me in the right direction? What am I doing wrong?
That happens because the first call of you constructor is implicit super()
Quote from the Java Tutorials:
If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.
You need to make a parameterless constructor in your Circle class or change your Cylinder constructor like this:
public Cylinder(double r, double h) {
super(r);
height = h;
}
You're implicitly calling the super constructor with no argument, but there's no such constructor.
But you have a design problem : You're trying to use both composition and inheritance. One would be enough.
Using inheritance :
public class Cylinder extends Circle {
public double height;
public Cylinder(double r, double h) {
super(r);
height = h;
}
public double getVolume() {
return circleArea() * height;
}
}
Using composition (almost always better) :
public class Cylinder {
public Circle base;
public double height;
public Cylinder(double r, double h) {
height = h;
base = new Circle(r);
}
public double getVolume() {
return base.circleArea * height;
}
}
You don't need an explicit base field in Java when using inheritance. To initialise the base class (or "superclass"), you need to use the super statement in your child class constructor:
class Circle {
public Circle(double radius) {
// …
}
}
class Cylinder extends Circle {
public Cylinder(double radius, double height) {
super(radius); // calls the parent class constructor
// …
}
}
Alternately, you could use composition instead of inheritance - probably a better design in this case:
class Circle {
public Circle(double radius) { /* … */ }
}
class Cylinder { // no `extends` here
public Cylinder(Circle base, double height) {
// …
}
public Cylinder(double radius, double height) {
this(new Circle(radius)); // calls the above constructor
// …
}
}
(I'm omitting trivial assignments and fields in the above code sample for brevity.)
Problem 1:
The problem in your program is no default constructor present in your Circle. While creating the Cylinder object its looking for the default constructor in Circle.
if you modify your Circle as below it will work
class Circle {
public Circle(){
}
}
problem 2
There is "base.circleArea" method only present in Circle, you have forgot "()"
base.circleArea need to change to base.circleArea().
public class Cylinder extends Circle {
public double getVolume() {
return base.circleArea() * height;
}
}
Problem 3
Your Cylinder should be like below. You are already extended circle so no need to create variable Circle base inside Cylinder.
class Cylinder extends Circle {
public double height;
public Cylinder(double r, double h) {
super(r);
height = h;
}
public double getVolume() {
return circleArea * height;
}
}

Circle implementation - How to model in order to fetch this information

1. Find circle diameter from radius
2. Find circle diameter from perimeter
3. Find circle diameter from area
4. Find circle perimeter from diameter
5. Find circle perimeter from radius
6. Find circle radius from diameter
7. Find circle radius from perimeter
8. Find circle radius from area
Currently our model class is implemented like this..
class Circle {
double radius;
Circle (double r) {
}
// Solves 6,7,8
double getDiameter() {}
double getPerimeter() {}
double getArea() {}
// static functions to solve 1-5
// e.g. public static double getPermiter(double diameter) {..}
}
Is there a better way to model the above class, so that I can fetch the above information, since given a certain parameter (e.g. radius, diameter, area or perimeter) the user is expected to find other information.
I'd probably prefer a Circle class with a constructor using the radius. You can add static factory methods to create instances from the circumference and area.
public class Circle
{
double radius;
public Circle(double radius)
{
this.radius = radius;
}
public static Circle fromCircumference(double circumference)
{
return new Circle(circumference / (Math.PI * 2));
}
public static Circle fromArea(double area)
{
return new Circle(Math.sqrt(area / Math.PI));
}
public double getCircumference()
{
return 2 * Math.PI * radius;
}
public double getRadius()
{
return radius;
}
public double getDiameter()
{
return 2 * radius;
}
public double getArea()
{
return Math.PI * radius * radius;
}
}
I would implement all 8 methods as static public methods inside the Circle class (or maybe in an associate helper class) and also declare the get{Diameter,Perimeter,radius} by calling the proper static methods defined above:
public class Circle {
double radius;
public double getPerimeter() {
return getPerimeterFromRadius(radius);
}
// ...
public static double getPerimeterFromRadius(double radius) {
return 2 * Math.PI * radius;
}
}
As I understand, you don't always need a circle itself, but, for instance, you want to count potential circle area by given radius.
I'd rather move all these static functions to a separate utility class. By convention, such class name is a plural form of a class or interface with which it's used. So, it will be named Circles.
public class Circles {
public static double diameterFromRadius(double radius) {...}
public static double diameterFromPerimeter(double perimeter) {...}
public static double perimeterFromArea(double area) {...}
...
}
If you still need class Circle for some reasons then consider to make your circle immutable (if it is not) i.e. remove any setters and make all fields final.
public class Circle {
final double radius;
public Circle (double r) {
this.radius = r;
}
public double getRadius() {
return radius;
}
}

Categories