作业介绍
这是一道直接回答的题目:
现有Person类,里面有方法run, eat, Student类继承了Person类,并重写了run方法,自定义了study方法。试写出对象向上转型和向下转型的代码,并写出对象可以各自调用哪些方法,并写出方法输出什么。
代码部分
package com.jin.homework;
/**
* @author 大力pig
*/
public class TestPerson {
public static void main(String[] args) {
//向上转型, 父类的引用指向子类的对象;
Person1 p = new Student();
p.run();
p.eat();
//向下转型, 子类的引用指向父类的对象;
Student s = (Student) p;
s.run();
s.eat();
s.study();
}
}
class Person1{//父类
public void run(){
System.out.println("person run");
}
public void eat(){
System.out.println("person eat");
}
}
class Student extends Person1{//子类
@Override
public void run(){
System.out.println("student run");
}
public void study(){
System.out.println("student study");
}
}
结果