- class ExtendsDemo {
- public static void main(String[] args){
- Student s = new Student("张三",23);
- Teacher t = new Teacher("李四",35);
- Print(s);
- Print(t);
- }
- /*
- 楼主的问题是由于在下面的这个打印语句中发生了类型提升(多态),
- 而在这个Print方法中的输出语句中又没有将类型转换回来,也就是说,
- 编绎出现的错误是因为你的这个Person父类中并没有learn()和teache()的方法;
- 我在下面注释部分已经帮楼主作了更改:
- */
- private static void Print(Person p)
- {
- if(p instanceof Student)
- {
- Student s=(Student)p;//这里,将类型转为Student(),因为传入的是父类的类型Person;
- System.out.println(s.name+" "+s.age+" "+s.eat());//这里使用的是子类Student的方法;
- s.learn();
- }
- else if(p instanceof Teacher)
- {
- Teacher t=(Teacher)p;//这里,将类型转为Teacher(),因为传入的是父类的类型Person;
- System.out.println(t.name+" "+t.age+" "+t.eat());//这里使用的是子类Teacher的方法;
- t.teach();
- }
- else{ System.out.println("error");}
- }
- }
- class Person{
- public String name;
- public int age;
- public String eat(){
- return "吃饭";
- }
- }
- class Student extends Person{
- Student(String name,int age){
- this.name = name;
- this.age = age;
- }
- public void learn(){
- System.out.println("学习");
- }
- }
- class Teacher extends Person{
- Teacher(String name,int age){
- this.name = name;
- this.age = age;
- }
- public void teach(){
- System.out.println("教课");
- }
- }
复制代码 |