package inheritencelatest;
public class InheritenceLatest {
public static void main(String[] args) {
person p1=new person(12,"ekaf","atlanta","male");
employe e1=new employe(23,"ekaf","atlanta","male",12000);
e1.ageCategory();
e1.genderIdentity();
e1.display();
((employe)p1).display();
}
}
class person {
int age;
String name;
String Address;
String ageGroup;
protected String gender;
private String canNotBeAccesed; //cant be accessed by subclass
person(int age,String name,String Address,String gender) {
this.age=age;
this.name=name;
this.Address=Address;
this.gender=gender;
}
String ageCategory() {
if(age<10)
return("kid");
else if(age<20 &&age>10)
return("Teen");
else if(age<50&&age>20)
return("adult");
else
return("senior");
}
protected void genderIdentity() {
if("male".equals(gender))
System.out.println("male");
else if(gender=="female")
System.out.println("female");
else
System.out.println("Special");
}
}
class employe extends person {
double salary;
employe(int age,String name,String Address,String gender,int salary) {
super(age,name,Address,gender);
this.salary=salary;
this.name=name;
}
@Override
protected void genderIdentity() {
if(gender=="male")
salary=salary;
if(gender=="female")
salary=1.5*salary;
else
salary=2*salary;
}
void display() {
System.out.println(age +" " +name+" "+Address+" "+salary+" "+gender+ " "+ageGroup);
}
當我運行這段代碼我得到輸出:
男性
23 ekaf atlanat 24000.0男性空
異常在線程 「主要」 java.lang.ClassCastException: inheritencelatest.person無法轉換爲inheritencelatest.employe繼承權限.InheritenceLatest.main(InheritenceLatest.java:17)
我,懷疑是
如何薪水變成24000?爲什麼agecategory爲null,在我編寫e1.agecategory時沒有反對e1獲得ageGroup的值?爲什麼((employe)p1).display();正在引發異常?
可以使用什麼
person p2 = new employe(23,「ekaf」,「atlanat」,「male」,12000);?
「p1」是一個「人」,而不是「僱主」。 – tkausl
當您發佈代碼時,請更加努力地設置您的代碼格式。這一切都在這個時刻 - 這不像一個*最小*的例子來證明問題。 –
你也應該閱讀閱讀http://stackoverflow.com/questions/513832 –