Search code examples
javainheritancesubclasssuperclass

Is it possible to create a subclass which extends from another subclass?


I am still learning how to code java and had a question about how inheritance works. Class A is the parent class and Class B is the subclass which inherits all the methods from Class A. Suppose I create a third class, Class C. If I do Class C extends Class B, is this different than doing Class C extends Class A? If so, how? Thank You. (Sorry if the format sucked)


Solution

  • The simplest way to visualize this is to consider that inheritance is like a parent/child relationship. You can have Parent -> Child -> Grand Child, etc.

    When you have:

    class A {}
    class B extends A{}
    class C extends B{}
    

    C is like a grand child of A. And that means C inherits all the methods from B, including those methods that B itself inherited from A. In OOP words,C**is**A`.

    However, when you have

    class A {}
    class B extends A{}
    class C extends A{}
    

    C and B are sibling classes, meaning they both inherit A's methods, but they are incompatible with one another.


    In the first case, these are valid:

    C c = new C();
    c.methodFromA(); //C inherits methods from A by being its grand-child
    c.methodFromB(); //C inherits methods from B by being its child
    c.methodFromC();
    

    In the second case, however, when both B and C extends A directly:

    C c = new C();
    B b = new B();
    c.methodFromA(); //C inherits methods from A by being its child
    b.methodFromA(); //B inherits methods from A by being its child
    
    c.methodFromB(); //not allowed
    b.methodFromC(); //not allowed
    

    However, there's no direct relationship between B and C. These are invalid:

    B b = new B();
    C c = new C();
    
    b = (B) c; //invalid, won't compile
    
    A b = b;
    c = (C) b; //will compile, but cause a ClassCastException at runtime