EliiTryToLearn
EliiTryToLearn

Reputation: 125

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!

Upvotes: 3

Views: 95

Answers (2)

thedeg123
thedeg123

Reputation: 438

In the case of your example, the SubClass2 class extends SuperSub, meaning all methods called by an instance SuperSub2 will be functionally the same as those called by an instance SuperSub except for those which you've overwritten.

In the case of the variable subClass2 it is an instance of SubClass2 meaning it can call all methods of SuperSub as well as those of SubClass2.

For a method that exists in both classes, in your case overideThisMethod, the respective methods will be called based on what type your variable is. For the variable subClass2 it is an instance of class SubClass2 so it calls its respective method (and prints "from subclass2"). While the variable superSub is an instance of the SuperSub class so it calls the overideThisMethod variable in its own class and prints ("Printed from Superclass").

Upvotes: 2

SalvadorGomez
SalvadorGomez

Reputation: 562

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).

Upvotes: 4

Related Questions