lui*_*uiv 6 java compiler-construction inheritance constructor class
可能重复:
访问非重写的超类方法时使用'super'关键字
我是Java的新手,最近一直在阅读它,以获得更多关于语言的知识和经验.当编译器插入自动代码时,我有一个关于继承方法和扩展类的问题.
我一直在读,如果我用一些方法创建类A,包括让我们说一个方法checkDuePeriod()
,然后创建一个扩展类A及其方法的类B.
如果我然后checkDuePeriod()
在不使用super.checkDuePeriod()
语法的情况下调用类B中的方法,则在编译期间编译器将包含super.
之前checkDuePeriod()
或将super()
在编译类时自动包含构造函数的事实意味着super.
类B调用类A的方法的调用?
我对此有点困惑.提前致谢.
超类的常规方法的实现不会在子类中自动调用,但必须在子类的构造函数中调用超类的构造函数的形式.
在某些情况下,super()
隐含了调用,例如当超类具有默认(无参数)构造函数时.但是,如果超类中不存在默认构造函数,则子类的构造函数必须直接或间接调用超类构造函数.
默认构造函数示例:
public class A {
public A() {
// default constructor for A
}
}
public class B extends A {
public B() {
super(); // this call is unnecessary; the compiler will add it implicitly
}
}
Run Code Online (Sandbox Code Playgroud)
没有默认构造函数的超类:
public class A {
public A(int i) {
// only constructor present has a single int parameter
}
}
public class B extends A {
public B() {
// will not compile without direct call to super(int)!
super(100);
}
}
Run Code Online (Sandbox Code Playgroud)