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)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>