/*
学生案例,使用多态和抽象类实现
具体事务:基础班学员,就业班学员
共性:姓名,年龄,班级,学习,吃饭
*/
//学生类
abstract class Student
{ //成员变量
private String name;
private int age;
private String grade;
//构造方法
Student(){}
Student(String name,int age,String grade){
this.name=name;
this.age=age;
this.grade=grade;
}
//成员方法
abstract void study();
public void eat(){
System.out.println("去餐厅吃饭");
}
public void show(){
System.out.println(name+" "+age+" "+grade);
}
}
class Basic extends Student
{ //构造方法
Basic(){}
Basic(String name,int age,String grade){
super(name,age,grade);
}
//重写成员方法
public void study(){
System.out.println("学java");
}
}
class Employment extends Student
{
//构造方法
Employment(){}
Employment(String name,int age,String grade){
super(name,age,grade);
}
//重写成员方法
public void study(){
System.out.println("学Android");
}
}
class Test
{
public static void main(String[] args)
{
Student s1=new Basic("张三",20,"6期");
s1.show();
s1.eat();
Basic b=(Basic)s1;
s1.study();
method(new Employment("李四",22,"6期"));
}
public static void method(Student s){
s.show();
s.eat();
if (s instanceof Basic)
{
Basic b=(Basic)s;
b.study();
}
if (s instanceof Employment)
{
Employment e=(Employment)s;
e.study();
}
}
}
|
|