0

我有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"); 

}
4

1 回答 1

0

每个工程师都是一个,但不是每个都是工程师。现在将其翻译到您的 OO 域。你认为你总是可以投到PersonEngineer?即假设每个都是工程师

不,但你可以问你是工程师吗?

if(abc instanceof Engineer) {
  Engineer xyz = (Engineer) abc;
}

但你不必总是知道这一点。你可以问每个人的名字,不管那个人是不是工程师:

Person p = new Engineer();
p.getFirstName();
于 2012-08-27T17:24:40.683 回答