在实际操作中,多态可以让我不用关心某个对象到底是什么具体类型,就可以使用该对象的某些方法,而这些方法通过一个抽象类或者接口来实现,多态就是提供父类调用子类代码的一个手段而已
abstract class Person
{
private String name;
private int age;
Person(String name,int age)
{
this.name = name;
this.age = age;
}
abstract void say();
}
class Student extends Person
{
Student(String name,int age)
{
super(name,age);
}
public void say()
{
System.out.println("I'am a Student");
}
}
class Teacher extends Person
{
private String profession;
Teacher(String name,int age,String profession)
{
super(name,age);
this.profession = profession;
}
public void say()
{
System.out.println("I'am a Teacher");
}
}
class School
{
private String schoolname;
private Person person;
School(String schoolname,Person person)
{
this.schoolname = schoolname;
this.person = person;
}
public void foundPerson()
{
person.say();
}
}
public class TestPolymoph
{
public static void main(String[] args)
{
Student studnet = new Student("lisi",21);
Teacher teacher = new Teacher("dudu",29,"maths");
School school1 = new School("changning",studnet);
School school2 = new School("changning",teacher);
school1.foundPerson();//I'am a Student
school2.foundPerson();//I'am a Teacher
}
}
School方法传递了抽象类Person,具体调用时是根据具体的实际实例化的对象调用对应的方法
posted on 2007-12-03 11:26
凌晨风 阅读(1667)
评论(2) 编辑 收藏 所属分类:
Java学习笔记