Reputation: 197
I have a superclass Shape.Java that accepts color of a certain shape, and several subclasses that computes the area of different polygons. I created a main class, printing out different choices of polygons that the user wants to compute.
public static void choices() {
System.out.println("What do you want to compute?");
System.out.println("a. Rectangle");
System.out.println("b. Triangle");
System.out.println("c. Trapezoid");
}
I used a switch case for this.
case 'a': {
System.out.print("Enter width: ");
double width = input.nextDouble();
System.out.print("\nEnter height: ");
double height = input.nextDouble();
.....
}
Problem is, how am I gonna call my subclass Rectangle(that extends the superclass Shape) that contains the methods that will display the input of the user and compute the area? Is this correct?
Shape rec = new Rectangle();
If it is, when I compile it I get an error 'cannot find symbol constructor Rectangle...'
Please help.
Upvotes: 4
Views: 171
Reputation: 120198
You are doing it correctly. Your undefined symbol is probably the result of a bad or non-existent import; Perhaps Rectangle
is not compiling, or perhaps you do not have a public no-arg constructor on Rectangle.
Because of dynamic dispatch, when you do
Shape rec = new Rectangle();
The interpreter, at runtime, will look at rec
, and invoke the method on Rectangle
, if you are invoking a method that was defined on Shape
and then overwritten on Rectangle
.
Upvotes: 3