day09-多态的好处
This commit is contained in:
8
day10/src/com/inmind/duotai08/test/Assistant.java
Normal file
8
day10/src/com/inmind/duotai08/test/Assistant.java
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
package com.inmind.duotai08.test;
|
||||||
|
|
||||||
|
public class Assistant extends Employee{
|
||||||
|
@Override
|
||||||
|
public void work() {
|
||||||
|
System.out.println("辅导员在辅导学生");
|
||||||
|
}
|
||||||
|
}
|
||||||
46
day10/src/com/inmind/duotai08/test/Demo09.java
Normal file
46
day10/src/com/inmind/duotai08/test/Demo09.java
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
package com.inmind.duotai08.test;
|
||||||
|
/*
|
||||||
|
多态的核心好处可以概括为:**“以不变应万变”**—— 通过接口或者父类,应对具体实现的变化。
|
||||||
|
它让代码更简洁、更灵活、更易于扩展,是构建大型、可维护系统的关键技术。
|
||||||
|
*/
|
||||||
|
public class Demo09 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
//没有多态的代码编写
|
||||||
|
//创建出每个子类对象,固定地执行一段功能代码,调用子类的work
|
||||||
|
Teacher teacher = new Teacher();
|
||||||
|
|
||||||
|
Assistant assistant = new Assistant();
|
||||||
|
|
||||||
|
//以上代码没有多态,所以有50个子类,重复的代码就要编写或封装50次,太繁琐
|
||||||
|
//多态写法
|
||||||
|
Employee e1 = new Teacher();
|
||||||
|
Employee e2 = new Assistant();
|
||||||
|
dTWork(e1);
|
||||||
|
dTWork(e2);
|
||||||
|
dTWork(teacher);
|
||||||
|
dTWork(assistant);
|
||||||
|
}
|
||||||
|
|
||||||
|
//定义一个父类类型接收子类对象,多态的写法
|
||||||
|
private static void dTWork(Employee employee) {
|
||||||
|
System.out.println("hello");
|
||||||
|
System.out.println("world");
|
||||||
|
employee.work();
|
||||||
|
}
|
||||||
|
|
||||||
|
//定义一个重复调用的普通写法
|
||||||
|
/*private static void dWork1(Assistant assistant) {
|
||||||
|
System.out.println("hello");
|
||||||
|
System.out.println("world");
|
||||||
|
assistant.work();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void dWork(Teacher teacher) {
|
||||||
|
System.out.println("hello");
|
||||||
|
System.out.println("world");
|
||||||
|
teacher.work();
|
||||||
|
}*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
8
day10/src/com/inmind/duotai08/test/Employee.java
Normal file
8
day10/src/com/inmind/duotai08/test/Employee.java
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
package com.inmind.duotai08.test;
|
||||||
|
|
||||||
|
public abstract class Employee {
|
||||||
|
String name;
|
||||||
|
int age;
|
||||||
|
|
||||||
|
public abstract void work();//强制子类必须实现重写该方法
|
||||||
|
}
|
||||||
8
day10/src/com/inmind/duotai08/test/Teacher.java
Normal file
8
day10/src/com/inmind/duotai08/test/Teacher.java
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
package com.inmind.duotai08.test;
|
||||||
|
|
||||||
|
public class Teacher extends Employee{
|
||||||
|
@Override
|
||||||
|
public void work() {
|
||||||
|
System.out.println("老师在上课");
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user