Trying to understand class inheritance in Java
Let me say I have a super class
public class SuperSub { public void overideThisMethod(){ System.out.println("Printed from Superclass"); } }
I have a subclass like this,
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 output from running the program:
run: from subclass2 Printed from Superclass
The output should not be,
run: from subclass2 from subclass2
Thank you very much for any clarification, thank you!
Solution
Extension (also known as inheritance) does not modify the superclass, but actually creates a new class with the extension you defined, such as overwriting it
Therefore, both classes exist, and each class has its own logic
Here, you are creating a class called supersub, which prints "print from superclass" Then you use it as the basis to create another class subclass2, which "masks" (a.k.a. overrides) the basic behavior, in this case by printing "from subclass2" instead of
In this way, if you create an object of class supersub, it will still behave as supersub Respectively, if you create an object of subclass2 class, its behavior is like supersub. You define "extension" in subclass2 (in this case, it is the overridden behavior)