Java之对象转型

对象转型是Java语法中比较重要的一部分,以下是关于对象转型几点要了解的内容:

1)一个基类的引用类型变量可以“指向”其子类的对象;
2)一个基类的应用不可以访问其子类对象新增加的成员(属性和方法);
3)可以使用引用变量instanceof类名来判断该引用型变量所“指向”的对象是否属于该类或该类的子类;
4)子类的对象可以当做基类的对象来使用称作向上转型,反之成为向下转型。


下面用一个小程序来解释一下对象转型:

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

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

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

//在上面的类中:Animal是父类,Dog和Cat从Animal继承
//Animal的成员变量是name,Dog和Cat新增加属性eyeColor、furColor

public class Test {
	public static void main(String[] args) {
		Animal a = new Animal("name");							//	a是animal
		Cat c = new Cat("catname","blue");					//	c是cat
		Dog d = new Dog("dogname","black");					//	d是dog
		
		System.out.println(a instanceof Animal);		//	a是Animal,输出true
		System.out.println(c instanceof Animal);		//	c是cat,从animal继承,是animal,输出true
		System.out.println(d instanceof Animal);		//  d是dog,从animal继承。是animal,输出true
		System.out.println(a instanceof Cat);				//	a是Animal。是cat的父类,不是cat,输出false
		
//下面是重点
		a = new Dog("bigyellow","yellow");					//重新定义一只狗:name是bigyellow,furcolor是yelloe
//在这里要注意,由于a的数据类型animal,所以虽然a是新定义出来的狗,但a只能访问这个dog中属于animal的部分,即不能访问dog.furcolor
//这就是父类引用指向子类对象,它看不到单独属于子类的那部分内容
		System.out.println(a.name);									//可以访问a.name
		//System.out.println(a.furColor);						//不能访问a.furColor,若执行这句话会出错
		System.out.println(a instanceof Animal);		//a是一只狗,属于animal,输出true
		System.out.println(a instanceof Dog);				//a实际上是狗,所以输出true
		Dog d1 = (Dog)a;														//强制转换,d1是整个的狗,可以访问dog.furColor了
		System.out.println(d1.furColor);
	}
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值