java 抽象类、接口通过内部类作为方法的参数

参考文档:https://www.cnblogs.com/java-demo/articles/9142993.html

  1. public class Fun {
  2. public static void main(String[] args) {
  3. // Person p = new Person(); operatePerson(p); 这样也可以
  4. operatePerson(new Person());
  5. // Animal a = new Cat(); operateAnimal(a); 这样也可以
  6. operateAnimal(new Cat());
  7. // 扩展: 还可以通过内部类一次传入
  8. operateAnimal(new Animal() {
  9. @Override
  10. public void run() {
  11. System.out.println("get from inner class----cat");// 这个逗号别忘了加
  12. }
  13. });
  14. // 要求传入父类对象, 但可以传入任意的子类对象,这样就使得扩展性得到了提高
  15. // 如: operateAnimal(new Cat()); operateAnimal(new Dog());
  16. // operateAnimal(new Bird());
  17. // Smoking s = new Student(); operateSmoking(s); 这样也可以
  18. operateSmoking(new Student());
  19. // 扩展: 接口也可以同内部类传入
  20. operateSmoking(new Smoking() {
  21. @Override
  22. public void smoking() {
  23. System.out.println("get from inner class----smoking");
  24. }
  25. });
  26. }
  27. public static void operatePerson(Person p) {
  28. p.eat();
  29. System.out.println("operatePerson eat");
  30. }
  31. public static void operateAnimal(Animal a) {
  32. a.run();
  33. }
  34. public static void operateSmoking(Smoking s) {
  35. s.smoking();
  36. }
  37. }
  38. // 1. 普通类当作方法参数传入
  39. class Person {
  40. public void eat() {
  41. System.out.println("Person eat");
  42. }
  43. }
  44. // 2. 抽象类作为方法参数传入
  45. abstract class Animal {
  46. abstract void run();
  47. }
  48. class Cat extends Animal {
  49. @Override
  50. void run() {
  51. System.out.println("I am cat");
  52. }
  53. }
  54. // 3. 接口实现类的对象作为方法参数传入
  55. interface Smoking {
  56. public abstract void smoking();
  57. }
  58. class Student implements Smoking {
  59. public void smoking() { // 实现接口的方法的修饰符范围可以比接口的范围大
  60. System.out.println("in smoking");
  61. }
  62. }

输出:

20200109215937718.png

发表评论

表情:
评论列表 (有 0 条评论,15人围观)

还没有评论,来说两句吧...

相关阅读

    相关 抽象抽象方法接口

    抽象方法:使用abstract修饰的方法,没有方法体,只有声明。 抽象类:包含抽象方法的类就是抽象类、通过抽象类,我们可以做到严格限制子类的设计,使子类之间更加通用 •使用