建立TestInstance 类,在类中定义方法method1(Person e);
在method1中:
(1)根据e的类型调用相应类的getInfo()方法。
(2)根据e的类型执行:
如果e为Person类的对象,输出:“a person”;
如果e为Student类的对象,输出
“a student”
“a person ”
如果e为Graduate类的对象,输出:
“a graduated student”
“a student”
“a person”- package com.ex4.duotai;
- public class TestInstance {
- /**
- * @param args
- */
- public static void main(String[] args) {
- TestInstance ti=new TestInstance();
- Person p1=new Person();//这里报错。。。怎么回事?
- Student student=new Student();
- Graduate gra=new Graduate();
-
- ti.method1(p1);
- System.out.println();
-
- ti.method1(student);
- System.out.println();
-
- ti.method1(gra);
- System.out.println();
-
- ;
-
-
-
-
- }
- public void method1(Person e){
- String info=e.getInfo();
- System.out.println(info);
-
- }
- class Person {
- protected String name="person";
- protected int age=50;
- public String getInfo() {
- return "Name: "+ name + "\n" +"age: "+ age;
- }
- }
- class Student extends Person {
- protected String school="pku";
- public String getInfo() {
- return "Name: "+ name + "\nage: "+ age
- + "\nschool: "+ school;
- }
-
- }
- class Graduate extends Student{
- public String major="IT";
- public String getInfo()
- {
- return "Name: "+ name + "\nage: "+ age
- + "\nschool: "+ school+"\nmajor:"+major;
- }
- }
- }
复制代码 问题怎么解决啊
|