class Animal{
String name;
public Animal(String name){
this.name=name;
}
}
class Cat extends Animal{
String furcolor;
public Cat(String name,String furcolor) {
super(name);
this.furcolor=furcolor;
// TODO Auto-generated constructor stub
}
}
class Dog extends Animal{
String furcolor;
public Dog(String name,String furcolor) {
super(name);
this.furcolor=furcolor;
// TODO Auto-generated constructor stub
}
}
public class Test {
public static void main(String [] args){
Animal animal = new Animal("Animal");
Cat cat = new Cat("cat","white");
//animal 只可以访问子对象中的父类部分 但是animal实质上是一只猫
animal=cat;
System.out.println(animal.name);
//System.out.println(animal.furcolor);报错
//instanceof 是按照内存方面计算的 实际上相当于一只猫
System.out.println(animal instanceof Cat);//ture
Animal a1=cat;
//a1所在空间的内存中实际占量为Cat量,向下强制转化为Cat,原本专门属于Cat的成员变量变得可访
Cat cat1=(Cat)a1;
System.out.println(cat1.name);
System.out.println(cat1.furcolor);
System.out.println(cat1 instanceof Cat);//true
//关于instanceof关键字的用法
System.out.println(animal instanceof Animal);//true
System.out.println(animal instanceof Cat);//true
System.out.println(animal instanceof Dog);//false
System.out.println(cat instanceof Cat);//true
System.out.println(cat instanceof Animal);//true
//System.out.println(cat instanceof Dog);//报错
CheckAnimal(animal);
CheckAnimal(cat);
}
//提高程序的可扩展性
public static void CheckAnimal(Animal animal){
System.out.print(animal.name);
if(animal instanceof Dog){
System.out.println(" 我是一只狗");
}else if(animal instanceof Cat){
System.out.println(" 我是一个猫");
}else{
System.out.println(" 我就是一只动物");
}
}
}
java基础-类型转换
最新推荐文章于 2022-12-07 21:37:10 发布