Java之对象转型

Java之对象转型

1.一个基类的引用类型可以指向其子类的对象

2.一个基类的引用指向子类的对象时不可以访问其子类对象新增加的成员(属性和方法)

3.可以引用   变量  instanceof  类名   来判断该引用变量所指向的对象是否属于该类或该类的子类

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);
		eyesColor = c;
	}
}
class Dog extends Animal {
	public String furColor;
	Dog(String n,String c) {
		super(n);
		furColor = c;
	}
}
public class TestAnimal {
	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);//true
		System.out.println(c instanceof Animal);//true
		System.out.println(d instanceof Animal);//true
		System.out.println(a instanceof Cat);//false
		
		
		a = new Dog("bigyellow", "yellow");
		System.out.println(a.name);
		//System.out.println(a.furColor);
		System.out.println(a instanceof Animal);
		System.out.println(a instanceof Dog);
		
		Dog d1 = (Dog)a;
		System.out.println(d1.furColor);
		
	}
}

为什么注释掉的那一行会报错呢?我们分析一下:这是父类对象引用子类对象

a是一个Animal类型,它指向了一个Dog对象,但是在程序的运行中,会把它这只Dog当成一只普通的Animal来看,所以furColor就访问不了了,所以这句会报错。(橙色的线是它实际能访问的范围)

如果想访问它的furColor,就要加强制转换符。

Java之对象转型_第1张图片

举例:

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);
		eyesColor = c;
	}
}
class Dog extends Animal {
	public String furColor;
	Dog(String n,String c) {
		super(n);
		furColor = c;
	}
}
public class TestAnimal {
	public static void main(String[] args) {
		TestAnimal test = new TestAnimal();
		Animal a = new Animal("name");
		Cat c = new Cat("catname", "blue");
		Dog d = new Dog("dogname", "black");
		
		test.f(a);
		test.f(c);
		test.f(d);
	}
	
	public void f(Animal a) {
		System.out.println("name:"+a.name);
		if (a instanceof Cat) {
			Cat cat = (Cat) a;
			System.out.println(" "+cat.eyesColor+" eyes");
		}
		else if (a instanceof Dog) {
			Dog dog = (Dog) a;
			System.out.println(" "+dog.furColor+" fur");
		}
		
	}
}

f()方法的可扩展性比较好。但是并没有达到最好。



你可能感兴趣的:(java基础)