使用前面创建子类或者实现类的方式来编写代码,如下:
AnimalParent.java
- package com.面向对象.Demo38;
-
- public abstract class AnimalParent {
- public abstract void eat();
- }
Dog.java
- package com.面向对象.Demo38;
-
- public class Dog extends AnimalParent {
- @Override
- public void eat() {
- System.out.println("Dog-eat()");
- }
- }
Cat.java
- package com.面向对象.Demo38;
-
- public class Cat extends AnimalParent{
- @Override
- public void eat() {
- System.out.println("Cat-eat()");
- }
- }
Test.java
- package com.面向对象.Demo38;
-
- public class Test01 {
- public static void main(String[] args) {
- AnimalParent dog = new Dog();
- AnimalParent cat = new Cat();
- dog.eat();
- cat.eat();
- }
- }
问题:上述代码如果有很多的子类,要创建很多子类,还要继承 重写父类的抽象方法
解决:使用匿名内部类(不需要创建子类或者实现类)
AnimalParent.java
- package com.面向对象.Demo39;
-
- public abstract class AnimalParent {
- public abstract void eat();
- }
Test.java
- package com.面向对象.Demo39;
-
- public class Test01 {
- public static void main(String[] args) {
- AnimalParent dog = new AnimalParent() {
- @Override
- public void eat() {
- System.out.println("Dog-eat()");
- }
- };
- dog.eat();
- System.out.println("=================================");
-
- AnimalParent cat = new AnimalParent() {
- @Override
- public void eat() {
- System.out.println("Cat-eat()");
- }
- };
- cat.eat();
- System.out.println("=================================");
-
- AnimalParent man = new AnimalParent() {
- @Override
- public void eat() {
- System.out.println("Man-eat()");
- }
- };
- man.eat();
- }
- }
上述代码使用的匿名内部类创建了3个子类,Dog,Cat,Man,可以简化了创建子类或者实现类
下一篇文章:匿名内部类底层实现原理