黑马程序员技术交流社区

标题: 帮我看看这个程序的运行结果为什么会这样? [打印本页]

作者: lovecx24    时间: 2013-12-15 22:36
标题: 帮我看看这个程序的运行结果为什么会这样?
public class Parent{
public void method(){
   System.out.println("parent");
  }
public static void smethod(){
   Sysyem.out.println("static parent");
  }
}
public class Child extends parent{
public void method(){
   System.out.println("child");
  }
public static void smethod(){
   Sysyem.out.println("static child");
  }
}
public class test{
public static void print(String [] args){
   Child c=new Child();
   Parent p=(Parent)c;
   p.method();
   p.smethod();
  }
答案是:child,static parent


作者: ysunday    时间: 2013-12-15 22:51
多态吧,这句Parent p = (Parent)c;这句不强转也行,强转其实没啥用的,相当于Parent p = c; c = new Child();看这个不就是多态了(多态只有一种情况就是说这个函数是没用static修饰的,并且子类覆盖了父类,其余的情况都没有多态,声明的什么类型,就调用什么类型的方法),所以这个多态就调用了子类的方法,打印child,而smethod是个静态函数,不存在多态现象,所以,声明了是Parent类型的变量,就调用Parent类的方法,打印了static parent
作者: Faner    时间: 2013-12-15 22:53
Child c=new Child();    Parent p=(Parent)c;   楼主 这两句是什么意思呢??
作者: 胡永城    时间: 2013-12-15 23:27
答案在注释中,仔细看

public class Parent{
public void method(){//父类的方法
   System.out.println("parent");
  }
public static void smethod(){//父类的静态方法,静态不会被覆盖,此方法只属于parent
   Sysyem.out.println("static parent");
  }
}
public class Child extends parent{
public void method(){//子类覆盖父类的方法
   System.out.println("child");
  }
public static void smethod(){//子类静态的方法,静态不会被覆盖,此方法只属于Child
   Sysyem.out.println("static child");
  }
}
public class test{
public static void print(String [] args){
   Child c=new Child();//创建子类对象
   Parent p=(Parent)c;//父类引用指向子类对象,即使没有(Parent),也会自动转型,(自动类型提升)
   p.method();//调用覆盖的方法,看对象的实际类型,为Child
   p.smethod();//调用Parent的静态方法
  }






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2