在Java中, 向上转型(upcasting)和向下转型(downcasting)的前提,必须是有“继承关系”,向上转型是自动的,向下转型需要进行强转。
例如:
/**定义了一个“父”类*/
public class Father {
/**姓名*/
private String name;
/**年龄*/
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
/**重写toString 方法*/
public String toString() {
return "我叫:" + name + "今年" + age + "岁";
}
}
/**定义了一个“子”类*/
public class Son extends Father{
/**子类特有的“说你好”方法*/
public void sayHey() {
System.out.println("你好");
}
}
/**程序入口*/
public class Main {
public static void main(String [] args) {
/**父类引用型变量 father 指向 Son 在堆中new出来的实例*/
Father father = new Son(); //向上转型(自动)
father.setName("小丽");
father.setAge(18);
/**输出信息*/
System.out.println(father);
/**将父类引用类型的变量father 中的地址 赋给 子类引用类型的变量son
* 子类引用类型的变量son 指向 子类的实例
*/
Son son =(Son) father; //向下转型(强转)
/**执行子类特有方法*/
son.sayHey();
}
}
几句定义:
1 . 一个基类的引用类型变量可以“指向”其子类的对象
例如上面的:Father father = new Son();
2 . 一个基类的引用不可以访问其子类对象新增的成员(属性和方法)
如下:
Father father = new Son();
/**
*父类引用访问子类特有的sayHey方法;
* 报错(The method sayHey() is undefined for the type Father)
*/
father.sayHey();
如果代码较多,不确定引用变量是否属于该类或该类的子类,可以用instanceonf 判断 该引用型变量所“指向”的对象是否属于该类或该类的子类。
Father father = new Father();
Father fSon = new Son();
System.out.println((fSon instanceof Son)? true : false);//输出true
System.out.println((father instanceof Son)? true : false);//输出false
如有错误,还请指正,谢谢。