Reputation: 3
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.
Upvotes: 0
Views: 116
Reputation: 3
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
Upvotes: 0