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