- //老师学生案例,加入抽烟的功能
- //定义接口
- interface Smoking {
- public abstract void smoke ();
- }
- //定义抽象类,人类
- abstract class Person {
- //定义成员变量
- private String name;
- private int age;
- //定义构造方法
- public Person (){}
- public Person (String name,int age) {
- this.name = name;
- this.age = age;
- }
- //初始化
- public void setName(String name) {
- this.name = name;
- }
- public String getName(String name) {
- return name;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public int getAge(int age) {
- return age;
- }
- //成员方法
- public abstract void eat();
- public void sleep() {
- System.out.println("累了就睡觉");
- }
- }
- //定义老师类
- class Teacher extends Person {
- public Teacher (){}
- public Teacher (String name,int age) {
- super(name,age);
- }
- public void eat(){
- System.out.println("吃素");
- }
- }
- //定义学生类
- class Student extends Person {
- public Student (){}
- public Student(String name,int age) {
- super(name,age);
- }
- public void eat(){
- System.out.println("吃荤");
- }
- }
- //定义抽烟的学生和老师
- class SmokeStudent extends Student implements Smoking {
- public SmokeStudent(){}
- public SmokeStudent(String name,int age) {
- super(name,age);
- }
- public void smoke (){
- System.out.println("抽烟的学生");
- }
- }
- class SmokeTeacher extends Teacher implements Smoking {
- public SmokeTeacher(){}
- public SmokeTeacher(String name,int age) {
- super(name,age);
- }
- public void smoke (){
- System.out.println("抽烟的老师");
- }
- }
- //测试类
- class InterfaceTest {
- public static void main(String[] args) {
- //建立抽烟学生的对象,不用多态,用具体类
- SmokeStudent ss = new SmokeStudent("魏娜",27);
- System.out.println(ss.getName()+"----------"+ss.getAge());
- ss.sleep();
- ss.eat();
- ss.smoke();
-
- }
- }
复制代码
|
|