您的位置:首页 > 编程语言 > Java开发

java基础--对象转型和多态

2013-03-30 22:33 489 查看
对象转型(casting):

1、一个基类的引用类型变量可以是指向子类的对象。

2、一个基类引用不能访问子类对象新增加的成员(属性和方法)。

3、可以使用引用变量instaceof来判断该引用类型变量所“指向”的对象是否属于该类,或者该类的子类。



4、 子类对象可以作为基类对象使用,称为(upcasting)“向上转型”,基类对象当做来使用称为(downcasting)“强制转换”。



例如,代码如下:



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); 
			 eyeColor = c;
		}
	}
	Class Dog extends Animal
	{
		Public String furColor;
		Dog(String n, String c)
		{
			Super(n);
			furColor(c);
			
		}
		
	}
Pulic class Test
	{
		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.furname);
			System.out.println(a instanceof Animal);
			System.out.println(a instanceof Dog);
			Dog d1 = (Dog)a;//强制转换符。
			System.out.println(d1.furColor); 
		}
	}


内存分析:




父类引用指向子类的对象,只能看到父类的那部分,看不到子类的那部分。a只能看到名字。




强制转换后(向下转型)可以看到全部的内容。



很基础的东西,但很重要。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: