简体   繁体   中英

Why can we call super class methods in a subclass constructor?

I need a better explanation for this scenario. I do not know whether this is a feature provided by Java language itself

//super class
public class Student {
    public Student(){}

    public void display(){
        System.out.println("Hello from Student");
    }       

}

//Subclass
public class SeniorStudent extends Student {

    public SeniorStudent(){
        super();
        display();
    }

    public static void main(String[] args) {
        SeniorStudent st=new SeniorStudent();
    }
}

When I run the program, display() method is invoked. What is the logic going on here?

You call display method in the child class, but if you don't rewrite the display() method it automatically call the parent one. The construct of the class is the first portion being executed in a class. The logic under your piece of software is this:

  • Start executing main method where you create a new instance of seniorStudent
  • SeniorStudent constructor has been called and start to execute
  • The first thing the constructor of SeniorStudent do is to call the parent constructor (which do nothing)
  • Then after have executed whole parent constructor resume to execute SeniorStudent constructor where you call display method but SeniorStudent class doesn't have any display method so call it's parent display method.

So if you want to print in console "Hello from senior student" you have to change the senior student class like this

    public class SeniorStudent extends Student {

    public SeniorStudent(){
        super();
        display();
    }
    public void display(){
      system.out.println("Hello from senior Student");
    }

    public static void main(String[] args) {
        SeniorStudent st=new SeniorStudent();
    }
}

And if you put super.display() in the display method from SeniorStudent class you call parent display method and then execute senior student display method so the output would be something like

"Hello from Student"
"Hello from Senior Student"

Hope I was enought clear, but if you have some problem i'm glad to help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM