日期:2014-05-20  浏览次数:20697 次

有点问题没想明白
class   OldStudent{
public   String   toS(){
return   "it 's   class   OldStudent   ";
}
}

class   Student   extends   OldStudent{  
private   String   name   =   "hello ";  
private   int   age   =   10;  
public   String   fun(){  
return   "Student:   "+name+ "   age: "+age;  
}  

public   static   void   main(String[]   args){  
OldStudent   stu=new   Student();  
System.out.println(stu);   /*这里输出的结果表明stu是Student类,但是下句被注释的输出语句却通不过编译*/
//System.out.println(stu.fun());  
System.out.println(stu.toS());/*但这里的正确输出却表示stu是OldStudent类,而且如果我System.out.println((Student)stu.fun());也是不行的,必须要Student   stu2   =   (Student)stu;System.out.println(stu.fun());   才能正确输出*/

}
}
想问的是:到底OldStudent   stu=new   Student();   该怎么理解?为什么如注释里的写法都不对呀???
谢谢了~~~~~~~~~~~~~

------解决方案--------------------
OldStudent stu=new Student();
这就是传说中的多态的一种表现
用父类的引用指向子类的对象
多看看多态的内容吧
good luck!
------解决方案--------------------
参考这个帖子我的解释:
http://community.csdn.net/Expert/topic/5510/5510162.xml?temp=.7520258

class OldStudent{
public String toS(){
return "it 's class OldStudent ";
}
}

class Student extends OldStudent{
private String name = "hello ";
private int age = 10;
public String fun(){
return "Student: "+name+ " age: "+age;
}

public static void main(String[] args){
OldStudent stu=new Student();
System.out.println(stu); /*这里输出的结果表明stu是Student类,但是下句被注释的输出语句却通不过编译*/
//System.out.println(stu.fun());
=====> stu是类型为OldStudent的reference variable,通过它只能看到OldStudent中有定义的方法和变量。
System.out.println(stu.toS());/*但这里的正确输出却表示stu是OldStudent类,而且如果我System.out.println((Student)stu.fun());也是不行的,必须要Student stu2 = (Student)stu;System.out.println(stu.fun()); 才能正确输出*/
======> System.out.println(((Student)stu).fun()); 应该是可以的。

}
}
------解决方案--------------------
应该仔细读书研究啊。
------解决方案--------------------
Study the following sections of Java Language Specification:
(http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html)
8.3.3 Examples of Field Declarations
8.3.3.2 Example: Hiding of Instance Variables
8.4.8 Inheritance, Overriding, and Hiding
8.4.9 Overloading
8.4.10 Examples of Method Declarations