您的位置:首页 > 编程语言 > Java开发

Java多态的“向上转型”和“向下转型”

2018-02-02 13:53 357 查看
package com.general;

class Animal {
public void tell1(){
System.out.println("A--------tell1;");
}

public void tell2(){
System.out.println("A -------tell2");
}
}

class Dog extends Animal{
@Override
public void tell1(){
System.out.println("B --------tell1;");
}

public void tell3(){
System.out.println("B --------tell3;");
}
}

public class PolDemo1{
public static void main(String[] args){
//向上转型: 父类  父类对象 = 子类实例
//        Animal animal = new Dog();

Dog dog = new Dog();
Animal animal = dog;
animal.tell1();
animal.tell2();

System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&");
//向下转型:先向上转型才能向下转型 子类 = (子类)父类实例
Animal animal1 = new Dog();
Dog dog1 = (Dog) animal1;

dog1.tell1();
dog1.tell2();
dog1.tell3();
}
}
运行结果:
B --------tell1;
A -------tell2
&&&&&&&&&&&&&&&&&&&&&&&&&&
B --------tell1;
A -------tell2
B --------tell3;


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: