java对象转型

---恢复内容开始---

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

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

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

子类的对象可以当作基类的对象来使用称作向上转型,反之称为向下转型

将父类对象赋值给子类引用,那么是往下走,那么就是向下转型;那么反之,将子类对象赋值给父类引用,那么就是向上走,就是向上转型

Father f = new Son();//向上转型
Son s = (Son)f;//安全向下转型


Father f = new Father();//声明父类
Son s = (Son)f;//不安全向下转型,编译会过,运行会错


Father f = new Father();//声明父类
if(f instanceof Son){
    Son s = (Son)f;//安全向下转型,如果f不是Son的实例,那么就不会发生转型
}

作者:jsy_hello
链接:https://www.jianshu.com/p/5a24f9939bb7
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
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 Animal);//false
		
		
		
		//a作为子类狗的引用  但是不能访问子类的成员
		a = new Dog("bigyellow","yellow");
		System.out.println(a.name);//bigyellow
		//System.out.println(a.furname);//!error
		
		System.out.println(a instanceof Animal);//true
		System.out.println(a instanceof Dog);//true
		
		Dog d1 = (Dog)a;//要加强制转换符 进行对象转型  转型后可以访问子类的成员变量
		System.out.println(d1.furcolor);//yellow
	}
}

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;
	}
}

原文地址:https://www.cnblogs.com/lsswudi/p/11268119.html