简体   繁体   English

在子类中定义与超类构造函数不同的构造函数?

[英]Define constructor in subclass that is different from the superclass constructor?

I'm having this weird question on my homework assignment. 我在家庭作业中有一个奇怪的问题。 Below there is a class declaration. 下面是一个类声明。

public class A {
private String str;
private int num;
   public A ( String str, int num ) {
     this.str = str;
     this.num = num;
}

Now I need an implementation of a subclass that is inherited from the A class, but has a different constructor like so: 现在,我需要一个继承自A类的子类的实现,但是具有一个类似的构造函数:

public class B extends A {
private String str1;
   public B ( String str, String str1 ) {...}

// this is where the editor shows an error because class B constructor arguments are 
// different from the arguments in the class A constructor

but I need this constructor to be different. 但是我需要这个构造函数有所不同。 How can I do this? 我怎样才能做到这一点?

You need to call the super constructor explicitly: 您需要显式调用超级构造函数:

public class B extends A {
private String str1;
    public B ( String str, String str1 ) {
        super(str,0);
        //do what you want...
    }

First of all your Base class has custom constructor but doesnot have default, this will lead to compile error. 首先,您的Base类具有自定义构造函数,但没有默认构造函数,这将导致编译错误。 Derived class will call implicit default constructor of base class in first line of derived class constructor or you can call necessary base constructor (super(..)) depends on your needs, after that is calling constructor body that goes next. 派生类将在派生类构造函数的第一行中调用基类的隐式默认构造函数,或者您可以根据需要调用必要的基本构造函数(super(..)),然后再调用下一步的构造函数主体。 So it's not problem to have different constructors. 因此,拥有不同的构造函数不是问题。

You must use the super() statement : 必须使用super()语句:

public B ( String str, String str1 ) {

    //0 is the second int argument of the class A constructor
    super(str, 0);

    //do something with the str1
}

Because your class A doesn't have anymore the default no args constructor that is created by the compiler if you don"t have any constructor defined in your class 因为您的类A不再具有默认的no args构造函数 ,而该构造函数是在您的类中没有定义任何构造函数的情况下由编译器创建的

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM