1. 程式人生 > 其它 >內部類、區域性內部類、靜態內部類、匿名內部類

內部類、區域性內部類、靜態內部類、匿名內部類

 呼叫內部類比較特殊:OuterClass.InnerClass innerClass = outerClass.new InnerClass();

package com.fh.base;

public class OuterClass {
    private int i = 10;

    /**
     * 內部類
     */
    class InnerClass{
        public void inner_m1(){
            System.out.println("【內部類獲取外部類的私有屬性的值】="+i);
        }
    }
    
public void outer_local_m1(){ /** * 區域性內部類 */ class LocalClass{//區域性內部類上不能有修飾符,或者只能有個final修飾符 public int local_m1(){ System.out.println("【區域性內部類獲取外部類私有屬性】="+i); return (i + 100); } } LocalClass localClass
= new LocalClass(); int local_result = localClass.local_m1(); System.out.println("【呼叫區域性內部類方法的返回值+100】="+local_result); } /** * 靜態內部類 */ public static class StaticInnerClass{ int i = 1000; public void staticInner_m1(){ System.out.println("【靜態內部類】="+i); } }
/** * 匿名內部類 */ Thread thread = new Thread(new Runnable() { @Override public void run() { System.out.println("【匿名內部類】"); } }); /** * 匿名內部類 */ AnonymousClass anonymousClass = new AnonymousClass() { @Override public void anonymousClass_m1() { System.out.println("【匿名內部類】"); } }; public static void main(String[] args) { OuterClass outerClass = new OuterClass(); //呼叫內部類 OuterClass.InnerClass innerClass = outerClass.new InnerClass(); innerClass.inner_m1(); //通過外部類方法呼叫區域性內部類 outerClass.outer_local_m1(); //呼叫靜態內部類 StaticInnerClass staticInnerClass = new StaticInnerClass(); staticInnerClass.staticInner_m1(); //呼叫匿名內部類 Thread thread = outerClass.thread; thread.start(); //呼叫匿名內部類 AnonymousClass anonymousClass = outerClass.anonymousClass; anonymousClass.anonymousClass_m1(); } } interface AnonymousClass { void anonymousClass_m1(); }