我有2节公开课;人和工程师。Engineer 继承自 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");
}