有什么方法可以在 JAVA 中使用父 class 的对象调用子 class 的构造函数吗?

Is there any way to call constructor of child class using object of parent class in JAVA?

我在 Java 的作文上有问题。我想访问位于另一个 class 中的 class 的构造函数。 现在,如果我创建了一个父对象 class 并想访问子对象 class 的构造函数。有什么办法可以做到吗?

这是 classes 和 runner class 的代码。

package compositon.student;
public class phone {
    String countryCode;
    String number;
    public phone(){}//empty constructor
    public phone(String countryCode, String number)
    {
        this.countryCode = countryCode;
        this.number = number;
    }
}

package compositon.student;

public class address {
    String Street_address;
    String town;
    String city;
    String country;
    
    phone number  = new phone(); //object from class phone, by using composition of classes
    
    public static void main(String[] args) {
        address objAddress = new address();
        objAddress.number()
    }
}

当您说“parent”和“child”class 时,您是在暗示继承,但此处并非如此。您只是在使用合成:class“Phone”的 object 是 class“地址”的字段。

您可以像访问任何其他 属性 一样在 class 上访问 Phone object。

在您的示例中,objAddress.number() 在您的 address 实例上调用方法 number,该实例不存在。

您可以先创建 Phone object 并将其传递给地址构造函数,或者稍后在地址 object 上设置 Phone object .

public class Phone {
    String countryCode;
    String number;
    
    public Phone() {
        
    }

    public Phone(String countryCode, String number)
    {
        this.countryCode = countryCode;
        this.number = number;
    }
}

public class Address {
    String streetAddress;
    String town;
    String city;
    String country;
    Phone phone;
    
    public Address() {
        
    }

    public Address(String streetAddress, String town, String city, String country, Phone number) {
        this.streetAddress = streetAddress;
        this.town = town;
        this.city = city;
        this.country = country;
        this.phone = number;
    }

    public static void main(String[] args) {
        Phone phone = new Phone("+62", "4412557");
        Address address = new Address("Street", "Town", "City", "Country", phone);

        // Update the phone number for an address
        address.phone.number = "12345";

        // Replace the phone object entirely for an address
        address.phone = new Phone("+11", "12345");
        
        // Using default contructors
        Address secondAddress = new Address();
        secondAddress.phone = new Phone();
        secondAddress.phone.number = "12345";
        secondAddress.phone.countryCode = "+14";
    }
}