是否允许上课?

时间:2012-08-27 17:20:03

标签: oop class casting type-conversion

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

}

1 个答案:

答案 0 :(得分:0)

每个工程师都是,但不是每个都是工程师。现在将其翻译为您的OO域。你认为你可以随时将Person投射到Engineer吗?即假设每个都是工程师

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

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

但你并不总是要知道这一点。您可以向每个人询问姓名,无论该人是否是工程师都无关紧要:

Person p = new Engineer();
p.getFirstName();