Search code examples
javasuperclasssubclassing

Trying to understand class inheritance in java


lets say i have the super class

public class SuperSub {
  public void overideThisMethod(){
    System.out.println("Printed from Superclass");
  }
}

And i have a sub class like so,

public class SubClass2 extends SuperSub { 
  @Override
  public void overideThisMethod(){
    System.out.println("from subclass2");
  }
  public static void main(String[] args){
    SubClass2 subClass2= new SubClass2();
    subClass2.overideThisMethod();
    SuperSub superSub = new SuperSub();
    superSub.overideThisMethod();
  }
}

I get the output from when i run the program:

run:
from subclass2
Printed from Superclass

Should the output not instead be,

run:
from subclass2
from subclass2

Any clarification is greatly appreciated, thank you!


Solution

  • Extending (also called inheritance) does not modifies the super class, but actually creates a new one with the extensions you define, like the override there.

    So, both classes exist, each with its own logic.

    Here, you are creating a class called SuperSub that prints "Printed from Superclass". Then you are using that as a base to create another class SubClass2, which "masks" (a.k.a. overrides) the base behavior, in this case by printing "from subclass2" instead.

    That way, if you create an object of class SuperSub, it will still behave as SuperSub. Respectively, if you create an object of class SubClass2, it will behave like SuperSub with the "extensions" you define in SubClass2 (in this case the overridden behavior).