gpt4 book ai didi

java - 在 Java 中从父类调用子类构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:09:35 25 4
gpt4 key购买 nike

所以我正在学习 java 继承,但我遇到了一种我不知道如何解决的情况。

我想做的是从父类(super class)中调用子类构造函数。我不知道这是否有意义,但我会尝试用一个例子来解释我自己。

public class Phone {
private String brand;
private int weight;

public Phone(String brand, int weight) {
this.brand = brand;
this.weight = weight;
}

public Phone(String brand, int weight, String tech) {
// Here it is where I'm stuck
// Call SmartPhone constructor with all the parameters
}
}

public class SmartPhone extends Phone {
private String tech;

public SmartPhone(String Brand, int weight, String tech) {
super(brand, weight);
this.tech = tech;
}
}

我为什么要这样做?

我希望能够不必在主要方面与智能手机打交道。
我希望能够做到:

Phone nokia = new Phone("Nokia", 295); // <- Regular Phone Instance
Phone iphone = new Phone("iPhone", 368, "4G"); // <- SmartPhone instance

最佳答案

Phone iphone = new Phone("iPhone", 368, "4G"); // <- SmartPhone instance

这毫无意义。如果你想要一个SmartPhone实例,你必须调用

Phone iphone = new SmartPhone("iPhone", 368, "4G");

不能从父类(super class)构造函数调用子类构造函数。

如果你想让Phone的类型由传递的参数决定,你可以使用静态工厂方法:

public class PhoneFactory {

public static Phone newPhone (String brand, int weight) {
return new Phone(brand, weight);
}

public static Phone newPhone (String brand, int weight, String tech) {
return new SmartPhone(brand, weight, tech);
}
}

Phone nokia = PhoneFactory.newPhone("Nokia", 295); // <- Regular Phone Instance
Phone iphone = PhoneFactory.newPhone("iPhone", 368, "4G"); // <- SmartPhone instance

关于java - 在 Java 中从父类调用子类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47696031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com