Must every function in the subclass be defined in the superclass?

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!

Jon Skeet
people
quotationmark

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:

  • You should follow Java naming conventions (Shape and Square instead of shape and square)
  • You don't need semi-colons after class declarations
  • You should outdent the first line of each class declaration... it looks very odd at the moment.

people

See more on this question at Stackoverflow