父类:
         public String str(){ 
return "hello";

子类:
public String str(){ 
return "hello world";
}有趣么?简单的方法覆盖。test y = new xx();
System.out.println(y.str()); 
System.out.println(y.str2());编译不过,类型问题,test没有 str2 方法,虽然y有,但编译器把y当作test而不是xx。楼主看看基础吧。

解决方案 »

  1.   

    编译不过,类型问题,test没有 str2 方法,虽然y有,但编译器把y当作test而不是xx。
    -----------------------------------------------------------------------------楼上的,你编译了么?还是你看看基础吧!ps. 楼主,这就是多态啊。
      

  2.   

    不能编译,既然声明的是y是test, 那么就只能使用test的API,只不过它的实现可能不在test中而已,
    这个和接口一样的道理。
      

  3.   

    同意,不能编译,声明的是y是test,那么在编译期就选好了型,自然就没有str2 方法,如果覆盖了父类的方法,才存在动态选型的问题。
      

  4.   

    不能编译
    这个是多态:
    public class Test{
    public String str(){
    return "hello";
    }
    public String str2(){
      return "hello";
      }
    }public class xx extends Test{
    public static void main(String args[]){
    Test y = new xx();
    System.out.println(y.str());
    System.out.println(y.str2());
    }
    public String str(){
    return "hello world";
    }
    public String str2(){
    return "hello world";
    }
    }输出:
    hello world
    hello world
      

  5.   

    确实不能通过编译,y是test类型的,没有str2()这个方法。