Java多态-向上转型和向下转型

一、向上转型

public class Test1 {

	public static void main(String[] args) {
		Person p1 = new Student();//父类的引用指向子类的对象
		p1.eat();

	}

}

class Person {
	private String name;
	private int age;

	public void eat() {
		System.out.println("人吃饭!");
	}
	
	
}

class Student extends Person {
	
	public void eat() {
		System.out.println("学生吃营养餐!");
	}
	
	public void goToSchool() {
		System.out.println("学生上学!");
	}
	
}

运行上述代码结果是:

“学生吃营养餐!”

向上转型体现的是多态,父类的引用指向子类的对象

Student类继承自Person类,并重写eat方法,有了子类对象的多态后,在编译期,只能调用父类中声明的方法(比如就不能调用goToSchool方法),但在运行期,实际执行的是子类重写父类的方法

简记为:编译看左,运行看右

注意:对象的多态只适用于方法,不适应于属性(属性是编译和运行都看左

二、向下转型

向下转型的目的是为了能够使对象调用子类特有的属性,方法(比如就不能调用goToSchool方法),所以我们使用类型强转符来转换

package duotai;

public class Test1 {

	public static void main(String[] args) {
		Person p1 = new Student();//父类的引用指向子类的对象
		p1.eat();
		
		Student s1 = (Student)p1;//强转类型转换,向下转型
		s1.goToSchool();//调用Student类特有的方法

	}

}

class Person {
	private String name;
	private int age;

	public void eat() {
		System.out.println("人吃饭!");
	}
	
	
}

class Student extends Person {
	
	public void eat() {
		System.out.println("学生吃营养餐!");
	}
	
	public void goToSchool() {
		System.out.println("学生上学!");
	}
	
}

运行上述代码结果是

“学生吃营养餐!”

“学生上学!”

强转后我们就可以使用Student类特有的方法goToSchool了

注意:强转时可能会出现ClassCastEexception的异常,通常在强转前用instanceof()来判断对象的类型

posted @ 2021-07-29 14:41  oneMoe  阅读(85)  评论(0编辑  收藏  举报