向上转型

子类引用的对象转换为父类类型称为向上转型。通俗地说就是是将子类对象转为父类对象。此处父类对象可以是接口。

向上转型就是具体类向抽象类的转换。

语法:父类   对象  = new 子类();  例如 :Animal hern = new Dog(); //向上转型

注意:1、向上转型时,子类单独定义的方法会丢失。

            2、子类引用不能指向父类对象。

package A;

public class Human {

public void sleep() {
System.out.println("这是父类人类");
}
}

class Male extends Human{
public void sleep() {
System.out.println("男人类 sleep");
}
}

class Famale extends Human{
public void sleep() {
System.out.println("女人类 sleep");
}
}
package A;

class Animal{ //父类
public void Eat() { //成员方法
System.out.println("所有动物的父类,eat");
}
}

class Dog extends Animal{//子类继承父类
public void Eat() {//重写父类Eat方法
System.out.println("子类Dog重写父类Eat方法,eat");
}

public void Fly() {//新增子类方法
System.out.println("Dog类新增的方法,Fly");
}
}

public class Hern {

public static void Sleep(Human N) {
N.sleep();
}

public static void main(String[] args) {
// TODO Auto-generated method stub
Animal hern = new Dog(); //向上转型
hern.Eat();
//hern.Fly(); //报错,hern 虽指向子类对象,但此时子类作为向上的代价丢失和父类不同的fly()方法
Hern hern1 = new Hern();
hern1.Sleep(new Male()); //向上转型,即:Human obj = new Male();
hern1.Sleep(new Famale()); //向上转型

/*运行结果是:
子类Dog重写父类Eat方法,eat
男人类 sleep
女人类 sleep
*/

}

}


向下转型

向下转型是把父类对象转为子类对象。(注意!这里是有坑的。)

向下转型就是讲抽象类转换为具体类。

向下转型后因为都是指向子类对象,所以调用的全是子类的方法

语法:子类 对象 = (子类)父类对象;    例如:Dog hern2 = (Dog)hern; //向下转型

将父类对象强制转换为某个子类对象,这种方式称为显示类型转换。

注意: 1、向下转型的前提是父类对象指向的是子类对象(也就是说,在向下转型之前,它得先向上转型)

            2、向下转型只能转型为本类对象(猫是不能变成狗的)。

            3、子类对象是父类的一个实例,但是父类对象不一定是子类的实例。

            4、如果将父类对象直接赋予子类,会发生编译器错误,因为父类对象不一定是子类的实例。

package A;

class Animal{ //父类
public void Eat() { //成员方法
System.out.println("所有动物的父类,eat");
}
}

class Dog extends Animal{//子类继承父类
public void Eat() {//重写父类Eat方法
System.out.println("子类Dog重写父类Eat方法,eat");
}

public void Fly() {//新增子类方法
System.out.println("Dog类新增的方法,Fly");
}
}

public class Hern {

public static void Sleep(Human N) {
N.sleep();
}

public static void main(String[] args) {
// TODO Auto-generated method stub
Animal hern = new Dog();
hern.Eat(); //调用子类的方法
Dog hern1 = (Dog)hern;//向下转型
hern1.Eat(); //调用子类方法
hern1.Fly();

/*运行结果是:
子类Dog重写父类Eat方法,eat
子类Dog重写父类Eat方法,eat
Dog类新增的方法,Fly
*/

}

}