java基础-类型转换

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(" 我就是一只动物");
		}
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值