问题描述
penson 类(属性:namen ,gender,age;方法:say())
Father类 (属性:namen ,gender,age ;方法 : say ():chinese,drive():car)
son类(属性:namen ,gender,age ;方法: say():English,Chinese,drive():airplane,)
编写完成以上类,实现继承关系。
编写一个测试类 TestPerson,在测试类中实现多态-,Person 根据用户输入 (1 代表fathen,2代表son) 调用相应对象的方法。
代码
import java.util.Scanner;
public class TestPerson {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Please enter a number,1 represents father, 2 represents son");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
person p;
if(n==1) {
p=new father();
//强制性转换
father f=(father) p;
f.drive();
}else {
p=new son();
son s=(son) p;
s.drive();
}
p.say();
}
}
abstract class person{
private String namen,gender;
private int age;
//抽象
public abstract void say() ;
}
class father extends person{
public void say() {
System.out.println(" say Chinese");
}
public void drive() {
System.out.println(" drive car");
}
}
class son extends father{
public void say() {
System.out.println(" say English and Chinese");
}
public void drive() {
System.out.println(" drive airplane");
}
}