java 抽象构造函数java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13623522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
abstract constructor java
提问by Bohn
How do i get the sub constructor from second and third? Since public abstract first doesnt work?
我如何从第二个和第三个获得子构造函数?既然公共抽象首先不起作用?
public abstract class First {
public Point position;
public First() {} //how do i make this constructor like an abstract?
// so that it will go get Second constructor or Third
}
public class Second extends First {
public Second (Point x) {
position = x;
}
}
public class Third extends First {
public Third(Point x) {
position = x;
}
}
回答by Kevin Bowersox
Java will not allow you to access the constructor of a concrete class derived from the abstract class from within the abstract class. You can however, call the super classes (abstract class) constructor from the concrete class.
Java 不允许您从抽象类内部访问从抽象类派生的具体类的构造函数。但是,您可以从具体类调用超类(抽象类)构造函数。
public abstract class First{
public Point position;
public Plant(Point x) {
this.position = x;
}
}
public class Second extends First {
public Second(Point x) {
super(x);
}
}
回答by SJuan76
When creating a Second
or Third
object, the programmer must use one of the constructors defined for that class.
创建Second
or Third
对象时,程序员必须使用为该类定义的构造函数之一。
First
constructor will be called implicitly, if you don't do it explicitly using super
. No need to make it abstract, you can either leave it empty or just not define it (Java will assume the implicit default constructor which has no arguments and performs no actions).
First
构造函数将被隐式调用,如果您不显式使用super
. 无需使其抽象,您可以将其留空或不定义它(Java 将假定隐式默认构造函数没有参数且不执行任何操作)。