【java初学笔记4】马士兵-java-面向对象-37->38对象转移

1.对象转移与基础类型的转换类似,只不过这个是针对对象的类型转换;

2.一个基类的引用类型变量可以指向其子类的对象,也就是说基类可以把子类当做自己这个类的一个对象引用,但是有一些限制(见下条)。

   如Animal类的一个对象a,可以转化成Dog类的一个对象使用。

3.但是基类的引用不能其子类新增的变量和方法。也就是说,a这个Animal对象转化成Dog后可以当Animal用,但不可以当Dog来用;

4. 见下例:

class Animal{
	String name;
	public Animal(String name){
		this.name = name;
	}
}

class Dog extends Animal{
	String furcolor;
	public Dog(String name,String furcolor){
		super(name);
		this.furcolor = furcolor;
	}
}

class Cat extends Animal{
	String eyecolor;
	public Cat(String name,String eyecolor){
		super(name);
		this.eyecolor = eyecolor;
	}
}

public class TestCasting{


	public static void main(String[] args){
		Animal a = new Animal("Animal_Name");
		Dog d = new Dog("Dog_Name","Yellow");
		Cat c = new Cat("Cat_Name","Blue");

		System.out.println(a.name);
		System.out.println(d.name+"  "+d.furcolor);
		System.out.println(c.name+"  "+c.eyecolor);

		a = new Dog("Snow","White");
		System.out.println(a.name);
		//System.out.println(a.furcolor);//error
		System.out.println(a instanceof Animal);
		System.out.println(a instanceof Dog);

		Dog d2 = (Dog)a;
		System.out.println(d2.furcolor);

		TestCasting tc = new TestCasting();//记住,要调用main函数里面的方法,要先建立一个main类的对象,用该对象调用
		tc.getInfo(a);
		tc.getInfo(d);
		tc.getInfo(c);
		tc.getInfo(d2);
	}


	public void getInfo(Animal a){
		System.out.println("name is "+a.name);
		if(a instanceof Dog){
			Dog dog = (Dog)a;
			System.out.println("furcolor is "+dog.furcolor);
		}
		else if(a instanceof Cat){
			Cat cat = (Cat)a;
			System.out.println("eyecolor is "+cat.eyecolor);
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值