• JAVA基础(十三)


    抽象类与抽象方法(abstract关键字的使用)

    随着继承层次中一个个新子类的定义,类变得越来越具体,而父类则更一 般,更通用。类的设计应该保证父类和子类能够共享特征。有时将一个父 类设计得非常抽象,以至于它没有具体的实例,这样的类叫做抽象类。

    用abstract关键字来修饰一个类,这个类叫做抽象类。

            此类不能实例化

            抽象类中一定有构造器,便于子类实例化时调用(涉及:子类对象实例化的全过程)

            开发中,都会提供抽象类的子类,让子类对象实例化

    用abstract来修饰一个方法,该方法叫做抽象方法。

            抽象方法只有方法的声明,没有方法体。

    public abstract void eat(); 

            包含抽象方法的类,一定是一个抽象类,因为抽象方法无法调用

            反之,抽象类中可以没有抽象方法

            若子类重写了父类中所有的抽象方法,则子类可实例化。

            若子类没有重写了父类中所有的抽象方法,则此子类也是一个抽象类,需要使用abstract修饰

    示例代码:

    1. package com.xxx.java;
    2. public class AbstractTest {
    3. public static void main(String[] args) {
    4. // 一旦类抽象了,就不可实例化了
    5. // Person p1 = new Person();
    6. // p1.eat();
    7. }
    8. }
    9. abstract class Creature{
    10. public abstract void breath();
    11. }
    12. abstract class Person extends Creature {
    13. String name;
    14. int age;
    15. public Person() {
    16. super();
    17. }
    18. public Person(String name, int age) {
    19. super();
    20. this.name = name;
    21. this.age = age;
    22. }
    23. public void walk() {
    24. System.out.println("人走路");
    25. }
    26. // 不是抽象方法
    27. // public void eat() {
    28. //
    29. // }
    30. // 抽象方法
    31. public abstract void eat();
    32. }
    33. class Student extends Person {
    34. public Student() {
    35. super();
    36. }
    37. public Student(String name, int age) {
    38. super(name, age);
    39. }
    40. @Override
    41. public void breath() {
    42. System.out.println("学生呼吸新鲜空气");
    43. }
    44. public void walk() {
    45. System.out.println("学生走路");
    46. }
    47. public void eat() {
    48. System.out.println("学生应该吃有营养的食物");
    49. }
    50. }

    应用代码:

    之前的练习:几何图像

     父类的findArea()因为无法确定图像是什么,所有无法确定面积,之前我们将其返回值设为0.0,并在各个子类中重写该方法

    修改:

    1. package com.xxx.exer;
    2. public abstract class GeometricObject {
    3. protected String color;
    4. protected double weight;
    5. public GeometricObject(String color, double weight) {
    6. super();
    7. this.color = color;
    8. this.weight = weight;
    9. }
    10. public String getColor() {
    11. return color;
    12. }
    13. public void setColor(String color) {
    14. this.color = color;
    15. }
    16. public double getWeight() {
    17. return weight;
    18. }
    19. public void setWeight(double weight) {
    20. this.weight = weight;
    21. }
    22. public abstract double findArea() ;
    23. }

    abstract使用上的注意点:

            abstract无法修饰:属性、构造器、代码块、final的类等。

            abstract不能用来修饰私有方法、静态方法、final的方法。

    练习:

    编写一个Employee类,声明为抽象类,

    包含如下三个属性:name,id,salary。

    提供必要的构造器和抽象方法:work()。

    对于Manager类来说,他既是员工,还具有奖金(bonus)的属性。

    请使用继承的思想,设计CommonEmployee类和Manager类,要求类 中提供必要的方法进行属性访问。

    1. package com.xxx.exer1;
    2. public abstract class Employee {
    3. private String name;
    4. private int id;
    5. private double salary;
    6. public Employee() {
    7. super();
    8. }
    9. public Employee(String name, int id, double salary) {
    10. super();
    11. this.name = name;
    12. this.id = id;
    13. this.salary = salary;
    14. }
    15. public abstract void work();
    16. }
    1. package com.xxx.exer1;
    2. public class Manage extends Employee {
    3. private double bonus;
    4. public Manage(double bonus) {
    5. super();
    6. this.bonus = bonus;
    7. }
    8. public Manage(String name, int id, double salary, double bonus) {
    9. super(name, id, salary);
    10. this.bonus = bonus;
    11. }
    12. @Override
    13. public void work() {
    14. System.out.println("管理员工,提高生产效率");
    15. }
    16. }

    1. package com.xxx.exer1;
    2. public class CommonEmployee extends Employee {
    3. @Override
    4. public void work() {
    5. System.out.println("员工在一线车间生产产品");
    6. }
    7. }
    1. package com.xxx.exer1;
    2. public class EmployeeTest {
    3. public static void main(String[] args) {
    4. Employee manager = new Manage("Alkaid",1001,5000,50000);
    5. manager.work();
    6. CommonEmployee commonEmployee = new CommonEmployee();
    7. commonEmployee.work();
    8. }
    9. }

    抽象类的匿名子类

    其中的Person和Student类在示例代码中

    1. package com.xxx.java;
    2. public class PersonTest {
    3. public static void main(String[] args) {
    4. method(new Student()); // 匿名对象
    5. Worker worker = new Worker();
    6. method1(worker);//非匿名类的非匿名对象
    7. method1(new Worker());//非匿名类的匿名对象
    8. System.out.println("*************");
    9. //创建了匿名子类的对象:p
    10. Person p = new Person() {
    11. @Override
    12. public void eat() {
    13. System.out.println("吃東西");
    14. }
    15. @Override
    16. public void breath() {
    17. System.out.println("好好呼吸");
    18. }
    19. };
    20. method1(p);
    21. System.out.println("*************");
    22. //创建了匿名子类的匿名对象
    23. method1(new Person() {
    24. @Override
    25. public void eat() {
    26. System.out.println("吃好吃的东西");
    27. }
    28. @Override
    29. public void breath() {
    30. System.out.println("好好呼吸新鲜的空气");
    31. }
    32. });
    33. }
    34. public static void method(Student s) {
    35. }
    36. public static void method1(Person p) {
    37. p.eat();
    38. p.breath();
    39. }
    40. }
    41. class Worker extends Person {
    42. @Override
    43. public void eat() {
    44. System.out.println("工人吃饭");
    45. }
    46. @Override
    47. public void breath() {
    48. System.out.println("工人呼吸");
    49. }
    50. }

    多态的应用:模板方法设计模式(TemplateMethod)

    抽象类体现的就是一种模板模式的设计,抽象类作为多个子类的通用模板,子类在抽象类的基础上进行扩展、改造,但子类总体上会保留抽象 类的行为方式。

    解决的问题:

            当功能内部一部分实现是确定的,一部分实现是不确定的。这时可以把不确定的部分暴露出去,让子类去实现。

            换句话说,在软件开发中实现一个算法时,整体步骤很固定、通用,这些步骤已经在父类中写好了。但是某些部分易变,易变部分可以抽象出来,供不同子类实现。这就是一种模板模式。

    模板方法设计模式是编程中经常用得到的模式。各个框架、类库中都有他的 影子,比如常见的有:

            数据库访问的封装

            Junit单元测试

            JavaWeb的Servlet中关于doGet/doPost方法调用

            Hibernate中模板程序

            Spring中JDBCTemlate、HibernateTemplate等

    代码示例:

    1

            

    1. package com.xxx.java;
    2. public class TemplateTest {
    3. public static void main(String[] args) {
    4. SubTemplate t = new SubTemplate();
    5. t.spendTime();
    6. }
    7. }
    8. abstract class Template{
    9. //计算某段代码执行所花费的时间
    10. public void spendTime() {
    11. long start = System.currentTimeMillis();
    12. //不确定部分
    13. code();
    14. long end = System.currentTimeMillis();
    15. System.out.println("花费的时间为:" + (end - start));
    16. }
    17. public abstract void code();
    18. }
    19. class SubTemplate extends Template {
    20. @Override
    21. public void code() {
    22. for(int i = 2;i <= 1000;i++) {
    23. boolean isFlag = true;
    24. for (int j = 2; j < Math.sqrt(i); j++) {
    25. if(i % j == 0) {
    26. isFlag = false;
    27. break;
    28. }
    29. if(isFlag) {
    30. System.out.println(i);
    31. }
    32. }
    33. }
    34. }
    35. }

    2

    1. package com.xxx.java;
    2. //抽象类的应用:模板方法的设计模式
    3. public class TemplateMethodTest {
    4. public static void main(String[] args) {
    5. BankTemplateMethod btm = new DrawMoney();
    6. btm.process();
    7. BankTemplateMethod btm2 = new ManageMoney();
    8. btm2.process();
    9. }
    10. }
    11. abstract class BankTemplateMethod {
    12. // 具体方法
    13. public void takeNumber() {
    14. System.out.println("取号排队");
    15. }
    16. public abstract void transact(); // 办理具体的业务 //钩子方法
    17. public void evaluate() {
    18. System.out.println("反馈评分");
    19. }
    20. // 模板方法,把基本操作组合到一起,子类一般不能重写
    21. public final void process() {
    22. this.takeNumber();
    23. this.transact();// 像个钩子,具体执行时,挂哪个子类,就执行哪个子类的实现代码
    24. this.evaluate();
    25. }
    26. }
    27. class DrawMoney extends BankTemplateMethod {
    28. public void transact() {
    29. System.out.println("我要取款!!!");
    30. }
    31. }
    32. class ManageMoney extends BankTemplateMethod {
    33. public void transact() {
    34. System.out.println("我要理财!我这里有2000万美元!!");
    35. }
    36. }

    练习

    编写工资系统,实现不同类型员工(多态)的按月发放工资。如果当月出现某个 Employee对象的生日,则将该雇员的工资增加100元。

    实验说明:

    (1)定义一个Employee类,该类包含:

            private成员变量name,number,birthday,其中birthday 为MyDate类的对象; abstract方法earnings();

            toString()方法输出对象的name,number和birthday。

    (2)MyDate类包含:

             private成员变量year,month,day ;

            toDateString()方法返回日期对应的字符串:xxxx年xx月xx日

    (3)定义SalariedEmployee类继承Employee类,实现按月计算工资的员工处理。该类包括:private成员变量monthlySalary;

            实现父类的抽象方法earnings(),该方法返回monthlySalary值;toString()方法输 出员工类型信息及员工的name,number,birthday。

    (4)参照SalariedEmployee类定义HourlyEmployee类,实现按小时计算工资的 员工处理。该类包括:

            private成员变量wage和hour;

             实现父类的抽象方法earnings(),该方法返回wage*hour值;

            toString()方法输出员工类型信息及员工的name,number,birthday。

    (5)定义PayrollSystem类,创建Employee变量数组并初始化,该数组存放各 类雇员对象的引用。利用循环结构遍历数组元素,输出各个对象的类型,name,number,birthday,以及该对象生日。当键盘输入本月月份值时,如果本 月是某个Employee对象的生日,还要输出增加工资信息。

    提示:

    //定义People类型的数组People c1[]=new People[10];

    //数组元素赋值

    c1[0]=new People("John","0001",20);

    c1[1]=new People("Bob","0002",19);

    //若People有两个子类Student和Officer,则数组元素赋值时,可以使父类类型的数组元素指向子类。

    c1[0]=new Student("John","0001",20,85.0);

    c1[1]=new Officer("Bob","0002",19,90.5);

    代码

    1. package com.xxx.exer2;
    2. public abstract class Employee {
    3. private String name;
    4. private int number;
    5. private MyDate birthday;
    6. public Employee(String name, int number, MyDate birthday) {
    7. super();
    8. this.name = name;
    9. this.number = number;
    10. this.birthday = birthday;
    11. }
    12. public String getName() {
    13. return name;
    14. }
    15. public void setName(String name) {
    16. this.name = name;
    17. }
    18. public int getNumber() {
    19. return number;
    20. }
    21. public void setNumber(int number) {
    22. this.number = number;
    23. }
    24. public MyDate getBirthday() {
    25. return birthday;
    26. }
    27. public void setBirthday(MyDate birthday) {
    28. this.birthday = birthday;
    29. }
    30. @Override
    31. public String toString() {
    32. return "[name=" + name + ", number=" + number + ", birthday=" + birthday.toDateString();
    33. }
    34. public abstract double earnings();
    35. }
    1. package com.xxx.exer2;
    2. public class MyDate {
    3. private int year;
    4. private int month;
    5. private int day;
    6. public MyDate(int year, int month, int day) {
    7. super();
    8. this.year = year;
    9. this.month = month;
    10. this.day = day;
    11. }
    12. public int getYear() {
    13. return year;
    14. }
    15. public void setYear(int year) {
    16. this.year = year;
    17. }
    18. public int getMonth() {
    19. return month;
    20. }
    21. public void setMonth(int month) {
    22. this.month = month;
    23. }
    24. public int getDay() {
    25. return day;
    26. }
    27. public void setDay(int day) {
    28. this.day = day;
    29. }
    30. public String toDateString() {
    31. return year + "年" + month + "月" + day + "日";
    32. }
    33. }
    1. package com.xxx.exer2;
    2. public class HourlyEmployee extends Employee {
    3. private int wage; // 每小时的工作
    4. private int hour; // 月工作的小时数
    5. public HourlyEmployee(String name, int number, MyDate birthday) {
    6. super(name, number, birthday);
    7. }
    8. public HourlyEmployee(String name, int number, MyDate birthday,int wage,int hour) {
    9. super(name, number, birthday);
    10. this.wage = wage;
    11. this.hour = hour;
    12. }
    13. @Override
    14. public double earnings() {
    15. return wage * hour;
    16. }
    17. @Override
    18. public String toString() {
    19. return "HourlyEmployee [" + super.toString() + "]";
    20. }
    21. }
    1. package com.xxx.exer2;
    2. public class SalariedEmployee extends Employee{
    3. double monthlySalary; //月工资
    4. public SalariedEmployee(String name, int number, MyDate birthday) {
    5. super(name, number, birthday);
    6. }
    7. public SalariedEmployee(String name, int number, MyDate birthday,double monthlySalary) {
    8. super(name, number, birthday);
    9. this.monthlySalary = monthlySalary;
    10. }
    11. public double getMonthlySalary() {
    12. return monthlySalary;
    13. }
    14. public void setMonthlySalary(double monthlySalary) {
    15. this.monthlySalary = monthlySalary;
    16. }
    17. @Override
    18. public double earnings() {
    19. return monthlySalary;
    20. }
    21. @Override
    22. public String toString() {
    23. return "SalariedEmployee [" + super.toString() + "]";
    24. }
    25. }

    测试:

    1. package com.xxx.exer2;
    2. import java.util.Calendar;
    3. import java.util.Scanner;
    4. public class PayrollSystem {
    5. public static void main(String[] args) {
    6. //方式一
    7. // Scanner scan = new Scanner(System.in);
    8. // System.out.println("请输入当前的月份:");
    9. // int month = scan.nextInt();
    10. //方式二
    11. Calendar calendar = Calendar.getInstance();
    12. int month = calendar.get(Calendar.MONTH);
    13. System.out.println(month);
    14. Employee[] emps = new Employee[2];
    15. emps[0] = new SalariedEmployee("Tom",1002,new MyDate(1992,2,28),10000);
    16. emps[1] = new HourlyEmployee("Mike",1003,new MyDate(1999,8,28),50,240);
    17. for (int i = 0; i < emps.length; i++) {
    18. System.out.println(emps[i]);
    19. double salary = emps[i].earnings();
    20. System.out.println("月工资为" + salary);
    21. if(month++ == emps[i].getBirthday().getMonth()) {
    22. System.out.println("生日快乐,奖励100元");
    23. }
    24. }
    25. }
    26. }

    接口(interface)

    一方面,有时必须从几个类中派生出一个子类,继承它们所有的属性和方 法。但是,Java不支持多重继承。有了接口,就可以得到多重继承的效果。

    另一方面,有时必须从几个类中抽取出一些共同的行为特征,而它们之间又 没有is-a的关系,仅仅是具有相同的行为特征而已。例如:鼠标、键盘、打 印机、扫描仪、摄像头、充电器、MP3机、手机、数码相机、移动硬盘等都 支持USB连接。

    接口就是规范,定义的是一组规则,体现了现实世界中“如果你是/要...则 必须能...”的思想。继承是一个"是不是"的关系,而接口实现则是 "能不能" 的关系。

    接口的本质是契约,标准,规范,就像我们的法律一样。制定好后大家都要遵守

    接口的使用体现了多态性

    接口实际上定义了一种规范

    体会面向接口编程

    在java中,接口和类是并列的两个结构

            接口中不能定义构造器,意味着接口不可以实例化。

            接口通过让类去实现(implements)的方式来使用

                    如果实现类实现(类的重写)了接口中的所有抽象方法,则此实现类就可以实例化

                    如果实现类没有实现(类的重写)了接口中的所有抽象方法,则此实现类仍为一个抽象类

            接口采用多继承机制。

                    类可以实现多个接口

                    接口与接口之间可以多继承

                    抽象类也可以实现接口,抽象类可以继承非抽象的类

            接口的使用上也满足多态性

    书写格式:

    1. //类实现接口
    2. class Bullet extends Object implements Flyable,Attackable{
    3. //接口或父类定义的抽象方法
    4. }
    5. //接口继承接口
    6. interface CC extends AA,BB{
    7. //代码块
    8. }

    如何定义接口中的成员

            JDK7以前:只能定义全局常量和抽象方法

                    全局常量:public static final的,但是书写时可以省略不写public static final

                    抽象方法:public abstract的,但是书写时可以省略不写public abstract

            JDK8:除了定义全局常量和抽象方法之外,还可以定义静态方法、默认(不是缺省)方法

                    静态方法:接口中定义的静态方法只能通过接口来调用

                    默认方法:

                            通过实现类的实例对象,可以调用接口中的默认方法

                            如果实现类重写了接口中的默认方法,调用时,调用的是重写后的方法

                            若子类(实现类)继承的父类和实现的接口中声明了同名同参数的方法,子类在没有重写此方法的情况下,默认调用的是父类中的方法——类优先原则

                            如果实现类实现了多个接口,而这多个接口中定义了同名同参数的默认方法,那么实现类没有重写此方法的情况下,报错——接口冲突——必须在实现类中重写此方法

                            可以通过接口名.super.方法名调用接口中的默认方法

    面试题:抽象类和接口有哪些异同?

            同:

                    都不能实例化

                    都可以被继承

            异:

                    抽象类有构造器,接口不能声明构造器

                    接口可以多继承,抽象类只能单继承

    JAVA 7

    使用示例

    1. package com.xxx.java1;
    2. public class InterfaceTest {
    3. public static void main(String[] args) {
    4. System.out.println(Flyable.MAX_SPEED);
    5. System.out.println(Flyable.MIN_SPEED);
    6. // Flyable.MIN_SPEED = 10;
    7. System.out.println("***************");
    8. Plane plane = new Plane();
    9. plane.fly();
    10. }
    11. }
    12. interface Flyable {
    13. // 全局常量
    14. public static final int MAX_SPEED = 7900; // 第一宇宙速度
    15. // 书写时可以省略不写public static final
    16. int MIN_SPEED = 1; // 第一宇宙速度
    17. public abstract void fly();
    18. // 书写时可以省略不写public abstract
    19. void stop();
    20. }
    21. interface Attackable {
    22. void sttack();
    23. }
    24. class Plane implements Flyable {
    25. @Override
    26. public void fly() {
    27. System.out.println("飞机通过引擎起飞");
    28. }
    29. @Override
    30. public void stop() {
    31. System.out.println("驾驶员减速停止");
    32. }
    33. }
    34. abstract class Kite implements Flyable {
    35. @Override
    36. public abstract void fly();
    37. }
    38. class Bullet extends Object implements CC, Flyable, Attackable {
    39. @Override
    40. public void sttack() {
    41. }
    42. @Override
    43. public void fly() {
    44. }
    45. @Override
    46. public void stop() {
    47. }
    48. @Override
    49. public void method1() {
    50. }
    51. @Override
    52. public void method2() {
    53. }
    54. }
    55. //**********************************************
    56. interface AA {
    57. void method1();
    58. }
    59. interface BB {
    60. void method2();
    61. }
    62. interface CC extends AA, BB {
    63. }

    应用举例:

    1. package com.xxx.java1;
    2. public class USBTest {
    3. public static void main(String[] args) {
    4. Computer computer = new Computer();
    5. // 体现了接口的多态性
    6. // 1.创建了接口的非匿名实现类的非匿名对象
    7. Flash flash = new Flash();
    8. computer.transferDate(flash);
    9. // 2.创建接口的非匿名实现类的匿名对象
    10. computer.transferDate(new Printer());
    11. // 3.创建接口的匿名实现类的非匿名对象
    12. USB phone = new USB() {
    13. @Override
    14. public void start() {
    15. System.out.println("手机开始工作");
    16. }
    17. @Override
    18. public void stop() {
    19. System.out.println("手机停止工作");
    20. }
    21. };
    22. computer.transferDate(phone);
    23. // 4.创建接口的匿名实现类的匿名对象
    24. computer.transferDate(new USB() {
    25. @Override
    26. public void start() {
    27. System.out.println("mp4开始工作");
    28. }
    29. @Override
    30. public void stop() {
    31. System.out.println("mp4停止工作");
    32. }
    33. });
    34. }
    35. }
    36. interface USB {
    37. // 常量:定义了长、宽、最大最小的传输速度等
    38. void start();
    39. void stop();
    40. }
    41. class Computer {
    42. public void transferDate(USB usb) {
    43. usb.start();
    44. System.out.println("具体的传输数据的细节");
    45. usb.stop();
    46. }
    47. }
    48. class Flash implements USB {
    49. @Override
    50. public void start() {
    51. System.out.println("U盘开始工作");
    52. }
    53. @Override
    54. public void stop() {
    55. System.out.println("U盘结束工作");
    56. }
    57. }
    58. class Printer implements USB {
    59. @Override
    60. public void start() {
    61. System.out.println("打印机开始工作");
    62. }
    63. @Override
    64. public void stop() {
    65. System.out.println("打印机结束工作");
    66. }
    67. }

    JAVA8

    使用示例

    1. package com.xxx.java8;
    2. public interface CompareA {
    3. //静态方法
    4. public static void method1() {
    5. System.out.println("method1:北京");
    6. }
    7. //默认方法
    8. public default void method2() {
    9. System.out.println("method2:上海");
    10. }
    11. //省略了public修饰符
    12. //default不是权限修饰符 缺省!
    13. default void method3() {
    14. System.out.println("method3:上海");
    15. }
    16. }
    1. package com.xxx.java8;
    2. public interface CompareB {
    3. default void method3() {
    4. System.out.println("method3:南京");
    5. }
    6. }

    1. package com.xxx.java8;
    2. public class SuperClass {
    3. public void method3() {
    4. System.out.println("SuperClass:南京");
    5. }
    6. }

    测试

    1. package com.xxx.java8;
    2. public class SubclassTest {
    3. public static void main(String[] args) {
    4. SubClass1 s1 = new SubClass1();
    5. //接口中定义的静态方法只能通过接口来调用
    6. CompareA.method1();
    7. //s.method1();
    8. //通过实现类的实例对象,可以调用接口中的默认方法
    9. //如果实现类重写了接口中的默认方法,调用时,调用的是重写后的方法
    10. s1.method2();
    11. //若子类(实现类)继承的父类和实现的接口中声明了同名同参数的方法,子类在没有重写此方法的情况下,默认调用的是父类中的方法——类优先原则
    12. s1.method3();
    13. SubClass2 s2 = new SubClass2();
    14. //如果实现类实现了多个接口,而这多个接口中定义了同名同参数的默认方法,那么实现类没有重写此方法的情况下,报错——接口冲突
    15. //必须在实现类中重写此方法
    16. s2.method3();
    17. }
    18. }
    19. class SubClass1 extends SuperClass implements CompareA {
    20. public void method2() {
    21. System.out.println("SubClass:上海");
    22. }
    23. }
    24. class SubClass2 implements CompareA,CompareB {
    25. public void method2() {
    26. System.out.println("SubClass:上海");
    27. }
    28. @Override
    29. public void method3() {
    30. System.out.println("必须重写");
    31. }
    32. public void myMethod() {
    33. //调用接口中的默认方法
    34. CompareA.super.method2();
    35. }
    36. }

     应用举例

    1. package com.xxx.java8;
    2. interface Filial {// 孝顺的
    3. default void help() {
    4. System.out.println("老妈,我来救你了");
    5. }
    6. }
    7. interface Spoony {// 痴情的
    8. default void help() {
    9. System.out.println("媳妇,别怕,我来了");
    10. }
    11. }
    12. class Father {
    13. public void help() {
    14. System.out.println("儿子,救我媳妇!");
    15. }
    16. }
    17. public class Man extends Father implements Filial,Spoony {
    18. public void help() {
    19. System.out.println("我两个都救");
    20. Filial.super.help();
    21. Spoony.super.help();
    22. }
    23. public static void main(String[] args) {
    24. new Man().help();
    25. }
    26. }

    接口的设计模式:代理模式(Proxy)

    概述:

            代理模式是Java开发中使用较多的一种设计模式。代理设计就是为其他对象提供一种代理以控制对这个对象的访问。

    应用场景:

            安全代理:屏蔽对真实角色的直接访问。

            远程代理:通过代理类处理远程方法调用(RMI)

            延迟加载:先加载轻量级的代理对象,真正需要再加载真实对象,比如你要开发一个大文档查看软件,大文档中有大的图片,有可能一个图片有 100MB,在打开文件时,不可能将所有的图片都显示出来,这样就可以使用代理模式,当需要查看图片时,用proxy来进行大图片的打开。

    分类

            静态代理(静态定义代理类)

            动态代理(动态生成代理类)

                      JDK自带的动态代理,需要反射等知识

    使用示例:

    1

    1. package com.xxx.java1;
    2. public class NetworkTest {
    3. public static void main(String[] args) {
    4. new ProxyServer(new Server()).browse();
    5. }
    6. }
    7. interface Network{
    8. void browse();
    9. }
    10. //被代理类
    11. class Server implements Network{
    12. @Override
    13. public void browse() {
    14. System.out.println("真实服务器访问网络");
    15. }
    16. }
    17. //代理类
    18. class ProxyServer implements Network{
    19. private Network work;
    20. public ProxyServer(Network work) {
    21. super();
    22. this.work = work;
    23. }
    24. public void check() {
    25. System.out.println("联网之前的检查工作");
    26. }
    27. @Override
    28. public void browse() {
    29. check();
    30. work.browse();
    31. }
    32. }

    2

    1. package com.xxx.java1;
    2. public class StaticProxyTest {
    3. public static void main(String[] args) {
    4. Star s = new Proxy(new RealStar());
    5. s.confer();
    6. s.signContract();
    7. s.bookTicket();
    8. s.sing();
    9. s.collectMoney();
    10. }
    11. }
    12. interface Star {
    13. void confer();// 面谈
    14. void signContract();// 签合同
    15. void bookTicket();// 订票
    16. void sing();// 唱歌
    17. void collectMoney();// 收钱
    18. }
    19. class RealStar implements Star {
    20. public void confer() {
    21. }
    22. public void signContract() {
    23. }
    24. public void bookTicket() {
    25. }
    26. public void sing() {
    27. System.out.println("明星:歌唱~~~");
    28. }
    29. public void collectMoney() {
    30. }
    31. }
    32. class Proxy implements Star {
    33. private Star real;
    34. public Proxy(Star real) {
    35. this.real = real;
    36. }
    37. public void confer() {
    38. System.out.println("经纪人面谈");
    39. }
    40. public void signContract() {
    41. System.out.println("经纪人签合同");
    42. }
    43. public void bookTicket() {
    44. System.out.println("经纪人订票");
    45. }
    46. public void sing() {
    47. real.sing();
    48. }
    49. public void collectMoney() {
    50. System.out.println("经纪人收钱");
    51. }
    52. }

    接口的设计模式:工厂模式

    概述

            工厂模式:实现了创建者与调用者的分离,即将创建对象的具体过程屏蔽隔离 起来,达到提高灵活性的目的。

            其实设计模式和面向对象设计原则都是为了使得开发项目更加容易扩展和维 护,解决方式就是一个“分工”。

    工厂模式的分类:

            简单工厂模式:用来生产同一等级结构中的任意产品。(对于增加新的产品, 需要修改已有代码)

            工厂方法模式:用来生产同一等级结构中的固定产品。(支持增加任意产品)

            抽象工厂模式:用来生产不同产品族的全部产品。(对于增加新的产品,无 能为力;支持增加产品族)

    核心本质:

            实例化对象,用工厂方法代替 new 操作。

            将选择实现类、创建对象统一管理和控制。从而将调用者跟我们的实现类解耦。

    无工程模式示例:

    1. package com.xxx.java1;
    2. interface Car {
    3. void run();
    4. }
    5. class Audi implements Car {
    6. public void run() {
    7. System.out.println("奥迪在跑");
    8. }
    9. }
    10. class BYD implements Car {
    11. public void run() {
    12. System.out.println("比亚迪在跑");
    13. }
    14. }
    15. public class Client01 {
    16. public static void main(String[] args) {
    17. Car a = new Audi();
    18. Car b = new BYD();
    19. a.run();
    20. b.run();
    21. }
    22. }

    简单工厂模式示例:

    1. package com.xxx.jd1;
    2. interface Car {
    3. void run();
    4. }
    5. class Audi implements Car {
    6. public void run() {
    7. System.out.println("奥迪在跑");
    8. }
    9. }
    10. class BYD implements Car {
    11. public void run() {
    12. System.out.println("比亚迪在跑");
    13. }
    14. }
    15. //工厂类
    16. class CarFactory {
    17. //方式一
    18. public static Car getCar(String type) {
    19. if ("奥迪".equals(type)) {
    20. return new Audi();
    21. } else if ("比亚迪".equals(type)) {
    22. return new BYD();
    23. } else {
    24. return null;
    25. }
    26. }
    27. //方式二
    28. // public static Car getAudi() {
    29. // return new Audi();
    30. // }
    31. //
    32. // public static Car getByd() {
    33. // return new BYD();
    34. // }
    35. }
    36. public class Client02 {
    37. public static void main(String[] args) {
    38. Car a = CarFactory.getCar("奥迪");
    39. a.run();
    40. Car b = CarFactory.getCar("比亚迪");
    41. b.run();
    42. }
    43. }

    小结:

            简单工厂模式也叫静态工厂模式,就是工厂类一般是使用静态方法,通过接收的 参数的不同来返回不同的实例对象。

            缺点:对于增加新产品,不修改代码的话,是无法扩展的。违反了开闭原则(对扩展开放;对修改封闭)。

    工厂方法模式示例

    为了避免简单工厂模式的缺点,不完全满足 OCP(对扩展开放,对修改关闭)。 工厂方法模式和简单工厂模式最大的不同在于,简单工厂模式只有一个(对于一个项目或者一个独立的模块而言)工厂类,而工厂方法模式有一组实现了相同接口的工厂类。这样在简单工厂模式里集中在工厂方法上的压力可以由工厂方法模式里不同的工厂子类来分担。

    1. package com.xxx.gc;
    2. interface Car {
    3. void run();
    4. }
    5. //两个实现类
    6. class Audi implements Car {
    7. public void run() {
    8. System.out.println("奥迪在跑");
    9. }
    10. }
    11. class BYD implements Car {
    12. public void run() {
    13. System.out.println("比亚迪在跑");
    14. }
    15. }
    16. //工厂接口
    17. interface Factory {
    18. Car getCar();
    19. }
    20. //两个工厂类
    21. class AudiFactory implements Factory {
    22. public Audi getCar() {
    23. return new Audi();
    24. }
    25. }
    26. class BydFactory implements Factory {
    27. public BYD getCar() {
    28. return new BYD();
    29. }
    30. }
    31. public class Client {
    32. public static void main(String[] args) {
    33. Car a = new AudiFactory().getCar();
    34. Car b = new BydFactory().getCar();
    35. a.run();
    36. b.run();
    37. }
    38. }

    总结:

    简单工厂模式与工厂方法模式真正的避免了代码的改动了?没有。在简单工厂模式中,新产品的加入要修改工厂角色中的判断语句;而在工厂方法模式中,要么将判断逻辑留在抽象工厂角色中,要么在客户程序中将具体工厂角色写死(就像 上面的例子一样)。而且产品对象创建条件的改变必然会引起工厂角色的修改。 面对这种情况,Java 的反射机制与配置文件的巧妙结合突破了限制——这在 Spring 中完美的体现了出来。

    抽象工厂模式

    抽象工厂模式和工厂方法模式的区别就在于需要创建对象的复杂程度上。而且抽象工厂模式是三个里面最为抽象、最具一般性的。

    抽象工厂模式的用意为:给客户端提供一个接口,可以创建多个产品族中的产品对象

    而且使用抽象工厂模式还要满足一下条件:

            1) 系统中有多个产品族,而系统一次只可能消费其中一族产品。

            2) 同属于同一个产品族的产品以其使用。

    接口的相关练习

    面试题:排错

    1. interface A {
    2. int x = 0;
    3. }
    4. class B {
    5. int x = 1;
    6. }
    7. class C extends B implements A {
    8. public void pX() {
    9. //System.out.println(x); //x不明确
    10. System.out.println(super.x); //B中的x
    11. System.out.println(A.x); //A中的x
    12. }
    13. public static void main(String[] args) {
    14. new C().pX();
    15. }
    16. }

    注释代码中x不明确,编译错误

    练习2

    定义一个接口用来实现两个对象的比较。

            interface CompareObject{

                     public int compareTo(Object o); //若返回值是 0 , 代表相等; 若为正数,代表当 前对象大;负数代表当前对象小

             }         

    定义一个Circle类,声明redius属性,提供getter和setter方法

    定义一个ComparableCircle类,继承Circle类并且实现CompareObject接口。在 ComparableCircle类中给出接口中方法compareTo的实现体,用来比较两个圆的半 径大小。

    定义一个测试类InterfaceTest,创建两个ComparableCircle对象,调用compareTo 方法比较两个类的半径大小。

    思 考 : 参 照 上 述 做 法 定 义 矩 形 类 Rectangle 和 ComparableRectangle 类 , 在 ComparableRectangle类中给出compareTo方法的实现,比较两个矩形的面积大小。

    1. package com.xxx.exer3;
    2. public interface CompareObject {
    3. public int compareTo(Object o);
    4. }

    1. package com.xxx.exer3;
    2. public class Circle {
    3. private Double radius;
    4. public Circle() {
    5. super();
    6. }
    7. public Circle(Double radius) {
    8. super();
    9. this.radius = radius;
    10. }
    11. public Double getRadius() {
    12. return radius;
    13. }
    14. public void setRadius(Double radius) {
    15. this.radius = radius;
    16. }
    17. }
    1. package com.xxx.exer3;
    2. public class ComparableCircle extends Circle implements CompareObject{
    3. public ComparableCircle(double radius) {
    4. super(radius);
    5. }
    6. @Override
    7. public int compareTo(Object o) {
    8. if(this == o) {
    9. return 0;
    10. }
    11. if (o instanceof ComparableCircle) {
    12. ComparableCircle c = (ComparableCircle)o;
    13. //错误的,如2.3和2.1强转后为0
    14. // return (int)(this.getRadius() - c.getRadius());
    15. //正确的
    16. // if (this.getRadius() > c.getRadius()) {
    17. // return 1;
    18. // } else if(this.getRadius() < c.getRadius()){
    19. // return -1;
    20. // }else {
    21. // return 0;
    22. // }
    23. //当属性radius声明为包装类时,可以调用包装类的方法
    24. return this.getRadius().compareTo(c.getRadius());
    25. } else {
    26. // return 0;
    27. throw new RuntimeException("传入的数据类型不匹配");
    28. }
    29. }
    30. }

    1. package com.xxx.exer3;
    2. public class InterfaceTest {
    3. public static void main(String[] args) {
    4. ComparableCircle c1 = new ComparableCircle(2.3);
    5. ComparableCircle c2 = new ComparableCircle (2.5);
    6. int compareValue = c1.compareTo(c2);
    7. if(compareValue > 0) {
    8. System.out.println("c1大");
    9. }else if (compareValue < 0) {
    10. System.out.println("c2大");
    11. }else {
    12. System.out.println("一样大");
    13. }
    14. int compareValue1 = c1.compareTo(new String());
    15. System.out.println(compareValue1);
    16. }
    17. }

    类的成员之五:内部类

    当一个事物的内部,还有一个部分需要一个完整的结构进行描述,而这个内 部的完整的结构又只为外部事物提供服务,那么整个内部的完整结构最好使用内部类。

    在Java中,允许一个类的定义位于另一个类的内部,前者称为内部类,后者称为外部类。

    内部类的分类:局部内部类、成员内部类(静态、非静态)

    实例化内部类的对象

    1. //创建静态成员类的实例
    2. Person.Dog dog = new Person.Dog();
    3. dog.show();
    1. //创建非静态成员类的实例
    2. Person p = new Person();
    3. Person.Bird bird = p.new Bird();

                    作为外部类的成员

                            调用外部类的结构

                            可以被static修饰

                            可以被四种不同的权限修饰

                    作为一个类

                            类内可以定义属性、方法、构造器等

                            可以被final修饰,表示此类不能被继承,即不使用final,可以被继承

                            可以被abstract修饰为抽象类

    调用外部类的结构

    1. public void display(String name) {
    2. System.out.println(name);//形参
    3. System.out.println(this.name);//内部类的name
    4. System.out.println(Person.this.name);//外部类的name
    5. }

           

    1. package com.xxx.java2;
    2. public class InnerClassTest {
    3. public static void main(String[] args) {
    4. // 创建静态成员类的实例
    5. Person.Dog dog = new Person.Dog();
    6. dog.show();
    7. // 创建非静态成员类的实例
    8. Person p = new Person();
    9. Person.Bird bird = p.new Bird();
    10. bird.sing();
    11. bird.display("niao");
    12. }
    13. }
    14. class Person {
    15. String name = "人类";
    16. int age;
    17. public void eat() {
    18. System.out.println("人:吃饭");
    19. }
    20. // 成员内部类
    21. // 静态成员内部类
    22. static class Dog {
    23. String name;
    24. int age;
    25. public void show() {
    26. System.out.println("卡拉是条狗");
    27. }
    28. }
    29. // 非静态成员内部类
    30. class Bird {
    31. String name = "鸟";
    32. public void sing() {
    33. System.out.println("我是一只小小鸟");
    34. eat();// Person.this.eat();
    35. }
    36. public void display(String name) {
    37. System.out.println(name);//形参
    38. System.out.println(this.name);//内部类的name
    39. System.out.println(Person.this.name);//外部类的name
    40. }
    41. }
    42. public void method() {
    43. // 局部内部类
    44. class AA {
    45. }
    46. }
    47. {
    48. // 局部内部类
    49. class BB {
    50. }
    51. }
    52. public Person() {
    53. // 局部内部类
    54. class CC {
    55. }
    56. }
    57. }

    开发中如何使用局部内部类

    1. package com.xxx.java2;
    2. public class InnerClassTest1 {
    3. // 开发中很少见
    4. public void method() {
    5. // 局部内部类
    6. class BB {
    7. }
    8. }
    9. //返回一个实现了Comparable接口的类的对象
    10. public Comparable getComparable() {
    11. //方式一
    12. //创建一个实现了Comparable接口的类:局部内部类
    13. // class MyComparable implements Comparable{
    14. //
    15. // @Override
    16. // public int compareTo(Object o) {
    17. // return 0;
    18. // }
    19. //
    20. // }
    21. // return new MyComparable();
    22. //
    23. //方式二
    24. return new Comparable(){
    25. @Override
    26. public int compareTo(Object o) {
    27. return 0;
    28. }
    29. };
    30. }
    31. }

    总结:成员内部类和局部内部类,在编译后,都会生成字节码文件。

    格式:

            成员内部类:外部类$内部类名.class

            局部内部类:外部类$数字 内部类名.class

    注意点:

            在局部内部类的方法中,如果调用局部内部类所声明的方法中的局部变量的话要求此局部变量声明为final(

            JDK7及之前的版本,要求此局部变量显式声明为final

            JDK8及之后的版本,可以省略final的声明

  • 相关阅读:
    RabbitMQ 26问,基本涵盖了面试官必问的面试题
    MAUI Blazor 权限经验分享 (定位,使用相机)
    负载均衡器监控
    【无标题】
    rust变量与常量
    Docker已存在Nginx容器对宿主机映射容器的目录进行修改,完成不同前端项目的部署
    Python 图形化界面基础篇:使用框架( Frame )组织界面
    设备树的引进与体验_使用设备树时的驱动编程
    2023年8月京东大家电市场数据分析(京东数据开放平台)
    TDengine 3.0 三大创新详解
  • 原文地址:https://blog.csdn.net/m0_56413004/article/details/126183878