Java

以下Animal为父类,Dog,Cat作为子类,分别继承Animal

class Animal{
    public void shout(){
        System.out.println("叫了一声");
    }
}

class Dog extends Animal{
    public void shout() {
        System.out.println("旺旺旺");
    }
    public void seeDoor() {
        System.out.println("看门中");
    }
}

class Cat extends Animal{
    public void shout() {
        System.out.println("喵喵喵");
    }
}

总结:

  1. Dog对象转成Animal对象可行,如d2

      Cat对象转成Animal对象可行,如c2

  2. d2作为Animal对象转成Dog对象可行。如d3,且可执行一个Dog特有的方法

  3. c2作为Animal对象转成Dog对象,编译通过,运行报错,显示 java.lang.ClassCastException,类型转化出错

实例代码:

1. Dog对象转成Animal对象可行,如d2

    Cat对象转成Animal对象可行,如c2

public class TestPoym{
    public static void main(String[] args) {
        Dog d1 = new Dog();
        animalCry(d1);
        Animal d2 = new Dog();  //向上转型
        animalCry(d2);

      Animal c1 = new Cat();
      animalCry(c1);
      Animal c2 = new Cat();
      animalCry(c2);

    }
    
    static void animalCry(Animal a) {
        a.shout();
    }
}

结果:

2. d2作为Animal对象转成Dog对象可行。如d3,且可实现一个Dog特有的方法,看门

public class TestPoym{
    public static void main(String[] args) {
        Dog d1 = new Dog();
        animalCry(d1);
        Animal d2 = new Dog();  //向上转型
        animalCry(d2);
        Animal c1 = new Cat();
        animalCry(c1);
        Animal c2 = new Cat();
        animalCry(c2);
        
        Dog d3 = (Dog)d2;  //向下转型
        d3.seeDoor();
        
    }
    
    static void animalCry(Animal a) {
        a.shout();
    }
}

结果:

3.  c2作为Animal对象转成Dog对象,编译通过,运行报错,显示 java.lang.ClassCastException,类型转化出错

代码:

public class TestPoym{
    public static void main(String[] args) {
        Dog d1 = new Dog();
        animalCry(d1);
        Animal d2 = new Dog();  //向上转型
        animalCry(d2);
        Animal c1 = new Cat();
        animalCry(c1);
        Animal c2 = new Cat();
        animalCry(c2);
        
        Dog d3 = (Dog)d2;  //向下转型
        d3.setDoor();
        
        Dog c3 = (Dog)c2;  //编译通过,运行出错,显示强制转换出错
    }
    
    static void animalCry(Animal a) {
        a.shout();
    }
}

结果:

原文地址:https://www.cnblogs.com/kl-1998/p/10641089.html