Search code examples
javainheritancecastingextendsupcasting

Object of child class cannot call its own methods


If c is a ChildClass object then why can't it call methods of ChildClass? Like:

ParentClass c=new ChildClass(); //Here ChildClass extends ParentClass

In particular:

Object s=new StringBuffer();

Here s is object of StringBuffer, but s.append(null) is compile time error. Why so?


Solution

  • c is declared to be a ParentClass. Therefore, all the compiler knows about it is that it is a ParentClass or some subclass of it. Suppose some other statement reassigned c somewhere:

    c = new SomeOtherChildClass();
    

    which is legal, because SomeOtherChildClass is also a subclass of ParentClass, and you've told the compiler that c can be any ParentClass. Now, if the compiler sees

    c.methodOfChildClass();
    

    how will it know that c is a ChildClass and not a SomeOtherChildClass that doesn't have that method?

    P.S. If you're sure c is really a ChildClass, at some point, you can get it to call a ChildClass method by downcasting:

    ((ChildClass)c).methodOfChildClass();
    

    The cast will cause the compiler to see c as a ChildClass; at runtime, the program will check to make sure c really is a ChildClass or else the program will throw ClassCastException.