我想知道当有人super()
在从抽象类继承的类的构造函数中调用java 方法时会发生什么。众所周知,抽象类无法实例化,只能super
调用抽象类的构造函数。
让我们举个例子。
public abstract class Figure { // cant be instantiated
private type firstAttribute;
private type secondAttribute;
public Figure(type firstAttribute, type secondAttribute) {
this.fisrtAttribute = fisrtAttribute;
this.fisrtAttribute = fisrtAttribute;
}
protected abstract void anyMethod();
}
class Rectangle extends Figure {
public Rectangle(type firstAttribute, type secondAttribute) {
/*
* call the abstract class constructor but we know, a
* constructor is used to
* instantiate class and we can't instantiate an abstract class
*/
super(firstAttribute, secondAttribute);
// then what really happen ?
}
@override
....
}
抽象基类初始化了您在具体继承类中继承的所有属性,因此可以避免在初始化中重复代码
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句