内部类:
- public class B {
- public A getA(int num){
- return new A(num){
- };
- }
- }
- public class A {
- private int num;
- public A(int num){
- this.num = num;
- }
- public A(){
- }
- }
内部类:
- public class B {
- public A getA(final int num){
- return new A(num){
- public int getNum(){
- return num;
- }
- };
- }
- }
- public class A {
- private int num;
- public A(int num){
- this.num = num;
- }
- public A(){
- }
- }
-
匿名内部类:
- public class Painter {
- public Shape getShape(){
- return new Shape(){
- public void paint(){
- System.out.println("painter paint() method");
- } //复写Shape接口的方法
- }; // 匿名内部类
- public static void main(String [] args){
- Painter painter = new Painter();
- Shape shape = painter.getShape();
- shape.paint();
- }
- }
-
- public interface Shape {
- public void paint();
- }
注意,匿名内部类后面的分号不可缺少!
匿名类,顾名思义,就是没有名称。
getShape()方法里,就使用了匿名内部类。
创建了一个实现了Shape的匿名类的对象。
匿名类可以创建,接口,抽象类,与普通类的对象。创建接口时,必须实现接口中所有方法
匿名内部类通过实例初始化,可以达到类似构造器的效果:
- public A getA(){
- return new A(){
- int num = 0;
- String str;
- {
- str = "javaeye";
- System.out.println("hello robbin");
- }
- };
- }
用匿名内部类来改造工厂方法:
- public interface Service {
- public void method1();
- }
-
- public interface ServiceFactory {
- Service getService();
- }
-
- public class Implemention1 implements Service{
- public void method1(){
- System.out.println("In Implemention1 method method1()");
- }
- public static ServiceFactory factory = new ServiceFactory(){
- public Service getService(){
- return new Implemention1();
- }
- };
- }
-
- public class Implemention2 implements Service {
- public void method1(){
- System.out.println("in Implemention2 method method1()");
- }
- public static ServiceFactory factory = new ServiceFactory(){
- public Service getService(){
- return new Implemention2();
- }
- };
- }
-
- public class Test {
- public static void main(String []args){
- service(Implemention1.factory);
- service(Implemention2.factory);
- ServiceFactory factory1 = Implemention1.factory;
- Service service1 = factory1.getService();
- service1.method1();
- ServiceFactory factory2 = Implemention1.factory;
- Service service2 = factory2.getService();
- service2.method1();
- }
- }