//参考博客 http://blog.sina.com.cn/s/blog_81547cad01015o4t.html
package com.lyh;
/*
* 继承后的变量问题,重写方法, 与向上 向下 转型 问题
* */
class Human {
public int id = 10;
public void eat() {
System.out.println("human eat!");
}
}
class Man extends Human {
public int id = 20;
public void eat() {
System.out.println("man eat!");
}
}
class Feman extends Human {
public int id = 30;
public int name = 20;
public void eat() {
System.out.println("feman eat!");
}
public void eat(int b) {
System.out.println("feman run b!");
}
public void run() {
System.out.println("feman run!");
}
}
public class Extands {
public static void Duotai(Human human) {
human.eat();
}
public static void main(String[] args) {
// 继承问题
Man man = new Man();
System.out.println("man.id = " + man.id);
man.eat();
/*
* 输出: man.id = 20 man eat! 子类重写(覆盖)了父类方法,并用自己的id
*/
// 向上转型问题:父类引用指向子类对象
Human human = new Feman();
System.out.println("humam.id = " + human.id);// 这里会调用 父类的 id。
human.eat();
// human.eat(2); 向上转型丢失了 除了子类覆盖的其他方法 和 其他 父类没有的变量
// human.run(); 同上
// human.name; 同上
/*
* 输出: humam.id = 10 feman eat!
*/
// 向上转型的好处
Duotai(human);
Duotai(new Human());
Duotai(new Man());
Duotai(new Feman());
/*
* 这里以父类为参数,调有时用子类作为参数,就是利用了向上转型。这样使代码变得简洁。不然的话,
* 如果Duotai以子类对象为参数,则有多少个子类就需要写多少个函数。这也体现了JAVA的抽象编程思想。
*/
// 向下转型 : 与向上转型相反,即是把父类对象转为子类对象。
Human hfe = new Feman();// 向上转型
hfe.eat();
Feman fe = (Feman) hfe;// 强制转 向下转
fe.eat();
// 但是为了安全 我们要使用
if (hfe instanceof Feman) {
Feman fe_ = (Feman) hfe;
fe_.eat();
}
/*
* 输出: feman eat! feman eat!
*/
// Human hu = new Human();
// Feman fe_ = (Feman) hu;//是错误的
// fe_.eat(); 不安全的向下转型,编译无错但会运行会出错
/*
* 总结:
*
* 1。父类引用指向子类对象,而子类引用不能指向父类对象,除非正确向下转型。
*
* 2。把子类对象直接赋给父类引用叫upcasting向上转型,向上转型不用强制转换。
*
* 如:Father f1 = new Son();
*
* 3。把指向子类对象的父类引用赋给子类引用叫向下转型(downcasting),要强制转换。
*
* 如:f1 就是一个指向子类对象的父类引用。把f1赋给子类引用s1即 Son s1 = (Son)f1;
*
* 其中f1前面的(Son)必须加上,进行强制转换。
*/
}
}