我有2个公共课;人和工程师。工程师继承自Person类。 现在在main()我有一个人对象说
Person abc = new Person();
我试图将“abc”转换为工程师,即
Engineer xyz = (Engineer) abc;
问题: 这是合法的吗?我的理解是我做不到,因为“abc”可能有不同的属性。
的代码: 的
public class Person {
private String firstname;
private String lastname;
private String gender;
public Person(String first, String last, String gen) {
firstname = first;
lastname = last;
gender = gen;
}
public void setFirstName(String name) {
firstname = name;
}
public void setLastName(String name) {
lastname = name;
}
public void setGender(String gen) {
gender = gen;
}
public String getFirstName() {
return firstname;
}
public String getLastName() {
return lastname;
}
public String getGender() {
return gender;
}
public toString() {
return "firstname=" + firstname + "lastname=" + lastname + "gender=" + gender;
}
public class SoftwareEngineer extends Person {
public String teamname;
public String bestlanguage;
public SoftwareEngineer(String first, String last, String gen, String team, String lang) {
firstname = first;
lastname = last;
gender = gen;
teamname = team;
bestlanguage = lang;
}
public toString() {
return "firstname=" + firstname + "lastname=" + lastname + "gender=" + gender + "teamname=" + teamname + "bestlanguage=" + bestlanguage;
}
public void main() {
SoftwareEngineer aaron = new SoftwareEngineer('Aaron','Gottlieb','M','IPSupport','SQL');
Person andy = new SoftwareEngineer('Andy','Gardner','M','IP','Java');
Person pete = new Person("Pete", "G", "M");
Person personAaron = aaron;
SoftwareEngineer sePete = (SoftwareEngineer) pete;
SoftwareEngineer seAndy = (SoftwareEngineer) andy;
pete.teamname = "FooBar";
aaron.setLastName("Brian");
}
答案 0 :(得分:0)
每个工程师都是人,但不是每个人都是工程师。现在将其翻译为您的OO域。你认为你可以随时将Person
投射到Engineer
吗?即假设每个人都是工程师?
不,但你可以问 person :你是工程师吗?:
if(abc instanceof Engineer) {
Engineer xyz = (Engineer) abc;
}
但你并不总是要知道这一点。您可以向每个人询问姓名,无论该人是否是工程师都无关紧要:
Person p = new Engineer();
p.getFirstName();