class shape {
private String name;
public shape(){
System.out.println("in shape, default");
}
public shape(String n){
System.out.println("in shape, one parameter");
name=n;
}
public String getName(){
return name;
}
};
class square extends shape {
private int length;
public square(){
super("square");
}
public void f(){
System.out.println("in f, square!");
}
};
public class Test {
public static void main(String args[]){
shape newObject=new square();
System.out.println(newObject.getName());
newObject.f();
}
};
When I try to call the function f()
in the main method it throws an error, but when I define f()
in the superclass shape
, it works. Shape
is not an abstract class.
Can anyone explain to me why this is?
Thank you!
The problem is that the compile-time type of your newObject
variable is shape
. That means the only members that the compiler knows about are the ones in shape
, and that doesn't include f()
.
If you want to use members which are specific to a given class, you need to use a variable of that type, e.g.
square newObject = new square();
newObject.f(); // This is fine
As asides:
Shape
and Square
instead of shape
and square
)See more on this question at Stackoverflow