对象的转型--向上转型

父类
class Person{
	String name;
	int age;
	
	void introduce(){
		System.out.println("我的名字是" + name + ",我的年龄是" + age);
	}
}

子类
class Student extends Person{
	String address;
	void talk(){
		System.out.println("hello");
	}
	
	void introduce(){
		super.introduce();
		System.out.println("我的家在" + address);
	}
}


class Test{
	public static void main(String[] args){
		Student s = new Student();
		Person p = s;
		
		p.name = "Allan";
		p.age = 20;
		//p.address = "beijing";
		p.introduce();
		//p.talk();
	}
}

p.address = "beijing";p.talk();
一个引用能够调用哪些成员(变量和函数),取决于这个引用的类型。
因为Person类中无address和talk(),所以不能调用。

p.introduce();
一个引用调用的是哪一个方法,取决于这个引用所指向的对象。
因为父类和子类都有introduce(),而父类对象p指向了子类对象s,所以调用的是子类对象的方法introduce()

Student s = new Student();Person p = s;这两句可以直接写为Person p = new Student();

猜你喜欢

转载自317324406.iteye.com/blog/2240041