<java編程語言 >
多太中的一種情況
在類的多太中,域是由他引用的類型決定那個版本,而方法則是由對象的真實類決定的。這和接口中使用的一樣。
測試代碼如下:
class Father{
public String str="father";
public void fun(){
System.out.println("Father : " + str);
}
}
class ChildOne extends Father{
public String str="childone";
public void fun(){
System.out.println("ChildOne : " + str);
}
}
public class TestClassProMeth {
public static void main(String args[]){
ChildOne childone = new ChildOne();
Father father = childone;
father.fun();
childone.fun();
System.out.println(father.str + '\n' + childone.str);
}
}
結(jié)果:
ChildOne : childone
ChildOne : childone
father
childone
接口:
在接口中的聲明的域是是一個常量(public static final),他的方法不能夠有其他的修飾符,隱式為public,也不能夠被擁有定義實現(xiàn)符的修飾如:native,synchronized,strictfp也不能夠是靜態(tài)的,因為靜態(tài)方法不能夠抽象方法。
繼承接口:如果接口聲明了一個和繼承來的常量名相同,則無論他的類型如何都將被隱藏,并且當(dāng)他們的類型不一致時,編譯出錯。
測試如下:
interface Super{
public static final String name = "super";
void fun();
}
interface Entend extends Super{
String name = "entend";
String str = Super.name + '\n' + name;
void fun();
}
class Realize implements Entend{
public void fun(){
System.out.println(Super.name + '\n' + Entend.name + '\n' + str);
}
}
public class TestInterface {
static String name ="testinterface";
public static void main(String args[]){
Realize real = new Realize();
real.fun();
System.out.println(Realize.name + '\n' + ((Super)real).name);
}
}
結(jié)果:
super
entend
super
entend
entend
super
posted on 2005-07-30 21:03
sky 閱讀(148)
評論(0) 編輯 收藏