在JAVA中,有没有办法使用父类的对象调用子类的构造函数?
我在Java的合成方面有一个问题。我想访问位于另一个类中的类的构造函数。 现在,如果我创建了一个父类的对象,并希望访问子类的构造函数。有什么可能的办法吗 下面是类和runner类的代码在JAVA中,有没有办法使用父类的对象调用子类的构造函数?,java,class,composition,Java,Class,Composition,我在Java的合成方面有一个问题。我想访问位于另一个类中的类的构造函数。 现在,如果我创建了一个父类的对象,并希望访问子类的构造函数。有什么可能的办法吗 下面是类和runner类的代码 package composition.student; 公用电话{ 字符串国家代码; 字符串编号; 公用电话(){}//空构造函数 公用电话(字符串国家代码、字符串号码) { this.countryCode=countryCode; 这个数字=数字; } }当你说“父类”和“子类”时,你是在暗示继承,这里不
package composition.student;
公用电话{
字符串国家代码;
字符串编号;
公用电话(){}//空构造函数
公用电话(字符串国家代码、字符串号码)
{
this.countryCode=countryCode;
这个数字=数字;
}
}
当你说“父类”和“子类”时,你是在暗示继承,这里不是这样。您只是在使用组合:类“Phone”的对象是类“Address”的字段
您可以像访问任何其他属性一样访问类上的Phone对象
在您的示例中,objAddress.number()
调用address
实例上不存在的number
方法
您可以先创建Phone对象并将其传递给Address构造函数,或者稍后在Address对象上设置Phone对象
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";
}
}
所以一个
地址
包含一个电话
,你想从地址
内部访问电话
的构造器,是吗?是的,没错……好吧,看来你已经这样做了。问题是什么?但如何在main方法中传递值?我无法在objAddress.number()中传递任何内容。它给出了一个错误。我应该在创建对象时使用变量吗?我想要它,这样我就可以像这样做objAddress.number(“+62”,“4412557”);当从类创建对象时,构造函数方法会自动调用。