简体   繁体   English

如何为抽象类的子类声明默认构造函数?

[英]How do I declare a default constructor for sub-class of abstract class?

The following doesn't work for me in Java. 以下内容在Java中对我不起作用。 Eclipse complains that there is no such constructor. Eclipse抱怨没有这样的构造函数。 I've added the constructor to the sub-class to get around it, but is there another way to do what I'm trying to do? 我已经将构造函数添加到子类中来解决它,但是还有另一种方法可以做我想做的事情吗?

public abstract class Foo {
    String mText;

    public Foo(String text) {
        mText = text;
    }  
}

public class Bar extends Foo {

}

Foo foo = new Foo("foo");

You can't instantiate Foo since it's abstract. 由于Foo是抽象的,因此无法实例化。

Instead, Bar needs a constructor which calls the super(String) constructor. 相反, Bar需要一个构造函数,该构造函数调用super(String)构造函数。

eg 例如

public Bar(String text) {
   super(text);
}

Here I'm passing the text string through to the super constructor. 在这里,我将text字符串传递给超级构造函数。 But you could do (for instance): 但是您可以这样做(例如):

public Bar() {
   super(DEFAULT_TEXT);
}

The super() construct needs to be the first statement in the subclass constructor. super()构造必须是子类构造函数中的第一条语句。

You can't instantiate from an abstract class and that's what you are trying here. 您不能从抽象类实例化,这就是您在这里尝试的方法。 Are you sure that you didn't mean: 您确定您不是故意的:

Bar b = new Bar("hello");

??? ???

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Java子类中调用该方法? - How do I call the method in the sub-class in java? 为什么类的子类必须是静态的才能在类的构造函数中初始化子类? - Why does a sub-class class of a class have to be static in order to initialize the sub-class in the constructor of the class? 如何强制实现接口或扩展抽象类的子类的类必须提供默认构造函数? - How do I enforce that a class implementing an interface or a subclass extending an abstract class must provide a default constructor? 如何从原始列表类中获取给定子类的元素列表? - How do I get a List of elements of a given sub-class from the original List Class? 如何确保从子类(Java)中的方法在抽象超类中调用某些方法 - How to ensure a certain methods gets called in abstract super-class from method in sub-class (Java) 如何将平面JSON反序列化为子类的多个实例? - How do I deserialize flat JSON into multiple instances of a sub-class? 如何访问子类的变量? - How can I access variables of a sub-class? 我应该对应该由子类指定的数据使用抽象方法还是实例变量? - Should I use an abstract method or an instance variable for data that should be specified by sub-class? 如何在Java中选择子类 - How to choose a sub-class in Java 为什么在抽象类中需要构造函数? - Why do i need a constructor in an abstract class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM