一、对象转型  Casting 

//对象转型Casting 
class Animal{
    public String name;
    Animal(String name){
        this.name = name;
    }
}

class Cat extends Animal{
    public String eyesColor;
    Cat(String n, String c){
        super(n);
        eyesColor = c;
    }
}

class Dog extends Animal{
    public String furColor;
    Dog(String n, String c){
        super(n);
        furColor = c;
    }
}

public class Casting{
    public static void main(String[]args){
        Animal a = new Animal("name");
        Cat c = new Cat("catname", "blue");
        Dog d = new Dog("dogname", "black");
        
        System.out.println(a instanceof Animal);
        System.out.println(c instanceof Animal);
        System.out.println(d instanceof Animal);
        System.out.println(a instanceof Cat);
        
        a = new Dog("bigyellow","yellow");
        System.out.println(a.name);
        //System.out.println(a.furColor);    wrong
        System.out.println(a instanceof Animal);
        System.out.println(a instanceof Dog);
        Dog d1 = (Dog)a;
        System.out.println(d1.furColor);
    }
}
true
true
true
false
bigyellow
true
true
yellow
View Code

相关文章:

  • 2022-02-23
  • 2022-02-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-19
  • 2021-07-22
猜你喜欢
  • 2022-12-23
  • 2021-12-15
  • 2022-02-04
  • 2022-12-23
  • 2021-08-24
  • 2021-08-08
  • 2021-08-27
相关资源
相似解决方案