多態

class Father{
int age=59;//成員變量並初始化
public void speak(){
System.out.println("father speak()");
}
public static void method(){//靜態方法
System.out.println("father methpd()");
}
}
class Son extends Father{
int age=22;
public void speak(){
System.out.println("son speak()");
}
public void talk(){
System.out.println("son talk()");
}
public static void method(){
System.out.println("son methpd()");
}
}
class PolymTest{
public static void main(String[] args){
Father f=new Father();//沒有體現多態,只是通過父類引用調用父類方法
f.speak();
Father f2=new Son();//父類引用指向子類對象,體現多態
f2.speak();//調用方法,如果子類重寫了該方法,則調用子類的
System.out.println(f2.age);//59~成員變量沒有多態性
f2.method();//father method()~靜態方法沒有多態性
// f2.talk();//不能調用子類特有的方法, erry
Son s=new Son();
s.speak();
s.talk();
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章