两端代码,第一段代码如下:
class Father {public Father() {}
public void shout(Object word){
System.out.println("object father shout:"+word);
}}class Son extends Father{public Son() {}
public void shout(String word){
System.out.println("string son shout:"+word);
}}public class Dan{
public static void main(String[] args){
Son son=new Son();
Father father=son;
son.shout("hello");
father.shout("hello");
}
}
这段代码的输出结果是:
string son shout:hello
object father shout:hello第二段代码,代码如下:
public class Demo{
public static void main(String[] args){
Professor p=new Professor();
Teacher t=p;
System.out.println (t.Teaching("数学"));
System.out.println (p.Teaching("语文"));
}
} class Teacher{
protected String name;
public Teacher(){
}
public String Teaching(String className){
return "正在教小学"+className;
}
}class Professor extends Teacher{
public Professor(){
}
public String Teaching(String className){
return "正在教大学"+className;
}
}
输出结果如下:
正在教大学数学
正在教大学语文问题:
father.shout("hello");执行的时候是执行Father的shout方法,而第二段代码t.Teaching("数学")为什么执行的不是Teacher的Teaching方法?
class Father {public Father() {}
public void shout(Object word){
System.out.println("object father shout:"+word);
}}class Son extends Father{public Son() {}
public void shout(String word){
System.out.println("string son shout:"+word);
}}public class Dan{
public static void main(String[] args){
Son son=new Son();
Father father=son;
son.shout("hello");
father.shout("hello");
}
}
这段代码的输出结果是:
string son shout:hello
object father shout:hello第二段代码,代码如下:
public class Demo{
public static void main(String[] args){
Professor p=new Professor();
Teacher t=p;
System.out.println (t.Teaching("数学"));
System.out.println (p.Teaching("语文"));
}
} class Teacher{
protected String name;
public Teacher(){
}
public String Teaching(String className){
return "正在教小学"+className;
}
}class Professor extends Teacher{
public Professor(){
}
public String Teaching(String className){
return "正在教大学"+className;
}
}
输出结果如下:
正在教大学数学
正在教大学语文问题:
father.shout("hello");执行的时候是执行Father的shout方法,而第二段代码t.Teaching("数学")为什么执行的不是Teacher的Teaching方法?
Teacher t=p;
t表示的是一个Professor类对象的引用,当然调用Professor的Teaching方法了
上转型对象不能操作子类新增的成员变量和方法,但可以操作子类对象继承或重写的方法,
如果子类重写了父类的某个方法,
上转型对象调用方法时,一定调用的是这个重写的方法
明白了吧?
第一问题原因在于:
子类与夫类的方法结构形势不一样:
Father: public void shout(Object word){}
Son: public void shout(String word){}
参数不一样,所以继承时son没有覆盖夫类的方法。也就可以推论这样的结果:
Son类里有两个方法:
1.void shout(Object word){}//继承夫类Father的方法
2.void shout(String word){}//继承后添加的方法你可以这样调用试一试:
Son son = new Son();
String s = "Hello!";
son.shout(s);//will print son information
son.shout((Object)s);//will print father information