【问题标题】:How to create constructor for a subclass如何为子类创建构造函数
【发布时间】:2020-02-09 08:14:18
【问题描述】:
import java.util.*;

class A {

    protected int n;

    public A(int a) {
        n = a;
    }

    protected int disp() {
        return n;
    }
}

class B extends A {

    // what should i do here
}

public class Hello {

    public static void main(String[] args) {
        //Your Code Here
        int a =5;
        A obj= new B(a);
        System.out.print(obj.disp());
    }
}

【问题讨论】:

  • public B(A a)?如果您真的希望 B 保存其父类的实例,您还应该仔细考虑,这通常是不必要的。
  • 因为你为了extend class A,你必须理想地初始化Object A所以创建一个调用new B(int a){ this.super(a);}的构造函数
  • @SiddarthSreeni this 是多余的。 super(a) 就足够了

标签: java inheritance constructor


【解决方案1】:

重要的是A 使用其构造函数之一进行初始化。 没有必要子类B 中的构造函数与A 中构造函数的参数相匹配。因此,您可以在子类 B 中定义任何构造函数,但请确保在其中调用 super( <some int> )。

例如,即使以下也可以。

class B extends A {
    public B(){ //Default constructor
        super( 1 );
    }
}

还有,

  1. 如果子类B 中有多个构造函数,则每个构造函数都必须调用super( <some int> )。
  2. 如果父类A中有多个构造函数,那么在子类构造函数中,通过super( <params> )调用其中任意一个即可。

【讨论】:

    【解决方案2】:

    您应该在B 类中执行以下操作:

    class B extends A {
      public B(final int a) {
        super(a);
      }
    }
    

    这里发生的事情是我们正在调用父级 (A) 的构造函数

    【讨论】:

      猜你喜欢
      • 2019-08-28
      • 2018-10-15
      • 2016-11-15
      • 1970-01-01
      • 1970-01-01
      • 2017-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多