【发布时间】:2014-04-26 09:53:06
【问题描述】:
在下面的代码中,我有几个问题要问:
我无法将类Address 的对象作为参数传递给其子类EmployeeAddress 的构造函数。为什么这样 ?它给出了参数不匹配之类的错误..没有传递参数....
我想在 show 方法中调用 EmployeeAddress 类中的 Address 对象。该怎么做?
class Address {
public String street;
int pin;
String city;
Address(String street, int pin, String city) {
this.street = street;
this.pin = pin;
this.city = city;
}
}
class EmployeeAddress extends Address {
int empid;
public String empname;
Address add;
EmployeeAddress (int empid, String empname, Address add){
this.empid = empid;
this.empname = empname;
this.add = add;
}
void show() {
System.out.println("my name is " + empname + "and my empid is " + empid);
}
}
class Employee {
public static void main(String ar[]) {
Address ad1 = new Address("mystreet", 201301, "nyk");
EmployeeAddress a1 = new EmployeeAddress(123, "kin", ad1);
a1.show();
}
/*
* public String toString() { return
* "my name is "+a1.empname+"and my pin is "+ad1.pin ; }
*/
}
【问题讨论】:
-
请。改进您的格式和命名,使其符合 Java 编码风格约定。
-
测试中要调用什么地址方法?
-
为什么要将父对象作为参数传递给子对象?这是一个非常糟糕的设计。我建议宁愿改变你的设计
-
将
class test重命名为class EmployeeAddress。遵循良好的命名约定做法(继承+大写) -
除了
EmployeeAddress.add是错误的继承用法外,这种行为与向下转换非常相似,但需要额外的参数来从通用对象创建特化。当您在创建专业化对象时拥有有限的信息时,就会发生这种情况。不管是好是坏,我相信这种模式是可以接受的。这种方法的替代方法是使用 Composition 模式,但有时Composition 不适合您的情况,您仍然需要这种模式。
标签: java inheritance constructor