學習筆記——Java內部類練習題


1.嘗試在方法中編寫一個匿名內部類。

package com.lzw;

public class AnonymityInnerClass {
}
class OuterClass4{

	public OutInterface doit(final String s){
		return new OutInterface(){
			private int i=0;
			public int getValue(){
				System.out.println(s);
				return i;
				
			}
			public void f(){
				System.out.println("f()");
			}
		};
	}

}
interface OutInterface { // 定義一個接口
}

  匿名內部類:new OutInterface(){

  .......

  }寫在了外部類Outerclass4的方法中。

 

2.嘗試將主方法編寫在靜態內部類中。

package com.lzw;

public class StaticInnerClass {
    int x=100;
    static class Inner{
        void doitInner(){
            //System.out.println("外部類"+x);
        }
        public static void main(String args[]){
            System.out.println("a");
        }
    }
}

  注:靜態內部類的最大特征就是不能使用外部類的非靜態成員。

3.嘗試編寫一個靜態內部類,在主方法中創建其內部類的實例。

package test;
public class StaticInnerClass {
	static class a{
		void f(){
			System.out.println("f()");
		}
	}
	public static void main(String args[]){
		StaticInnerClass.a a=new a();
		a.f();
	}
	
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM