Java super()继承 [英] Java super() inheritance
问题描述
问题的简短摘要:我有一个由子类扩展的父类。
A short summary of the question: I have a parent class which is extended by a child class.
public class Parent{
public Parent(){
//constructor logic
}
}
这个子类使用super调用Parent的构造函数:
This child class calls the Parent's constructor using super:
public class Child extends Parent{
public Child(){
super();
}
}
我想知道我是否要扩展Child类如果我可以在Grandchild类的构造函数中调用super()方法:
I was wondering if I were to extend the Child class if I could call the super() method in the Grandchild class' constructor:
public class Grandchild extends Child{
public Grandchild(){
super();
}
}
推荐答案
super ()在继承上调用构造函数一级,如果有一个无参数构造函数,则隐式调用它。
super() is calling constructor one level up on the inheritance and it is called implicitly, if there is a no-arg constructor.
从最高级别的继承初始化对象,在您的情况下,它是对象>父>子>孙。
Objects are initialized from the top level of inheritance, in your case it is Object > Parent > Child > Grandchild.
来自文档:
If a constructor does not explicitly invoke a superclass constructor, the Java compiler
automatically inserts a call to the no-argument constructor of the superclass. If the super
class does not have a no-argument constructor, you will get a compile-time error. Object does
have such a constructor, so if Object is the only superclass, there is no problem.
这篇关于Java super()继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!