Java在方法作用域內建立的內部類

FrankYou發表於2016-11-03

在方法作用域內建立的內部類,用來實現一個介面

/**
 * Created by xfyou on 2016/11/3.
 * Java內部類演示
 */
public class Parcel3 {
    public Destination dest(String s) {
        /**
         * 在方法作用域內建立的內部類,用來實現一個介面
         */
        class PDestination implements Destination {
            private String lable;

            private PDestination(String lable) {
                this.lable = lable;
            }

            @Override
            public String readLabel() {
                return lable;
            }
        }

        // 返回內部類的一個例項物件
        return new PDestination(s);
    }
}

abstract class Contents {
    abstract public int value();
}

interface Destination {
    String readLabel();
}

 匿名類的建立

    public Contents cont(){
        /**
         * 建立從Contents 衍生出來的匿名類的一個物件
         */
        return new Contents() {
            @Override
            public int value() {
                return 0;
            }
        };
    }

 

相關文章