[英]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
不知道是不是Java语言本身提供的特性
//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.当我运行程序时,将调用
display()
方法。 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.您在子类中调用 display 方法,但如果您不重写 display() 方法,它会自动调用父类。 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所以如果你想在控制台中打印“Hello from Senior student”,你必须像这样改变高年级学生班级
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如果您将 super.display() 放在 SeniorStudent 类的显示方法中,您将调用父显示方法,然后执行高年级学生显示方法,因此输出将类似于
"Hello from Student"
"Hello from Senior Student"
Hope I was enought clear, but if you have some problem i'm glad to help you希望我说得够清楚了,但是如果您有问题,我很乐意为您提供帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.