【问题标题】:Using the extended class constructor使用扩展类构造函数
【发布时间】:2013-11-15 09:38:29
【问题描述】:

我想知道是否可以对一个类执行以下操作,如果可以的话,它会扩展 Java 中的另一个类。怎么样?:

public class HelloWorld {
    public HelloWorld() {
        A aClass = new A(22);
    }
}

public class A extends B {
    public A() {
        System.out.println(number);
    }
}

public class B {
    public int number;

    public B(int number) {
        this.number = number;
    }
}

【问题讨论】:

  • 问题出在哪里?
  • 这不会编译,因为A 必须调用接收int 参数的B 类的构造函数。

标签: java class methods constructor extends


【解决方案1】:

您的A 构造函数需要使用super 链接到B 构造函数。目前B 中唯一的构造函数采用int 参数,因此您需要指定一个,例如

public A(int x) {
    super(x); // Calls the B(number) constructor
    System.out.println(number);
}

请注意,由于您在 HelloWorld 中调用它的方式,我已将x 参数添加A 中。不过,您不必具有相同的参数。例如:

public A() {
    super(10);
    System.out.println(number); // Will print 10
}

然后调用它:

A a = new A();

Every 子类构造函数要么链接到同一类中的另一个构造函数(使用this),要么链接到超类中的构造函数(使用super 或隐式)作为构造函数中的第一条语句身体。如果链接是隐式的,它总是等同于指定super();,即调用无参数的超类构造函数。

更多详情请见section 8.8.7 of the JLS

【讨论】:

  • 我认为我的问题表述不正确。这是您描述的好方法,但我真正想要的不是调用实际的 A 构造函数,而只是调用 B 构造函数,通过用 A 制作一个对象。这就是 Extends 的重点。
  • @KevinJensenPetersen:你不能那样做。要构造A 的实例,您必须 调用A 构造函数...并且您不能将构造函数签名从一个类继承 到子类。
  • 我明白了.. 无论如何,谢谢,你的回答仍然帮助了我,并且可能是我会这样做的方式..
猜你喜欢
  • 2021-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-29
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 2019-01-07
相关资源
最近更新 更多