1 class Father 2 { 3 4 public static String getName() 5 { 6 return "father"; 7 } 8 } 9 10 class Children extends Father 11 { 12 public static String getName() 13 { 14 return "children"; 15 } 16 } 17 public class staticTest { 18 public static void main(String[] args) { 19 // TODO Auto-generated method stub 20 Father father=new Father(); 21 Father children=new Children(); 22 System.out.println(father.getName()); 23 System.out.println(children.getName()); 24 } 25 26 }
代码中子类和父类都声明为static的函数,注意static不依赖于对象的实例,而依赖于对象,声明对象的时候就分配空间。所以它是依赖于类的,Father children的时候就打印出Father的father.结果为 father father
去掉static才能实现多态。