1、介绍
①、匿名内部类是没有名字的内部类,因为没有名字所以没办法引用。必须在创建时,作为 new 语句的一部分来声明,只能使用一次
②、使用前提:必须继承一个父类或实现一个接口
2、结构
①、匿名内部类形式如下:
new 类或接口{
    //方法主体
}
3、代码示例
①、原始抽象类的基本实现
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 
 | public abstract class Animal {
 
 
 
 public abstract void eat();
 }
 
 public class Cat extends Animal {
 
 @Override
 public void eat() {
 System.out.println("猫吃鱼。。。。");
 }
 
 }
 
 public class TestCatMain {
 
 public static void main(String[] args) {
 Animal animal = new Cat();
 animal.eat();
 }
 }
 
 | 
备注:
    如果此处的Cat类只使用一次,那么将其编写为独立的一个类岂不是很麻烦?这个时候就引入了匿名内部类
②、在抽象类中使用内部类
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 
 | public abstract class Animal {
 
 
 
 public abstract void eat();
 }
 
 public class TestAnonymousInnerClassCatMain {
 
 public static void main(String[] args) {
 
 Animal animal = new Animal() {
 @Override
 public void eat() {
 System.out.println("在chou。。。。");
 }
 };
 
 animal.eat();
 
 }
 }
 
 | 
③、在接口上使用匿名内部类
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 
 | public interface IAnimal {
 
 
 
 void eat();
 }
 
 
 public class TestAnonymousInnerClassCatMain {
 
 public static void main(String[] args) {
 
 IAnimal iAnimal = new IAnimal() {
 @Override
 public void eat() {
 System.out.println("在接口中使用的匿名内部类。。。。");
 }
 };
 iAnimal.eat();
 }
 }
 
 | 
总结
- 匿名内部类不能有构造方法,但可以调用父类的构造方法。
- 匿名内部类不能定义任何静态成员,方法和类。
- 一般使用代码块为匿名内部类提供初始化工作