1. 程式人生 > >Java高階語法筆記-匿名類(Anonymous Class)

Java高階語法筆記-匿名類(Anonymous Class)

匿名類(Anonymous Class)
匿名內部類,簡稱匿名類:是內部類的一種化簡寫法。
基本寫法如下:
BaseType obj=new BaseType(){
//類的定義
}


Java專案中匿名類的寫法十分常見。


匿名內部類也是內部類,所以語法上和內部類一樣使用。
this.訪問本類物件的成員

OUTER.this訪問外部類OUTER物件的成員

AbstractClass.java

package my;

public abstract class AbstractClass
{
	public abstract void Print();
}

HelloWorld.java

package my;


public class HelloWorld
{
	public void CalledAbstractClassPrint() {
		AbstractClass Anonymous_Abstract=new AbstractClass() {

			@Override
			public void Print()
			{
				System.out.println("Anonymous_Abstract Called");
			}
			
		};
		Anonymous_Abstract.Print();
	}
	public void CalledNormalClassPrint() {
		NormalClass Anonymous_Normal=new NormalClass() {
			public void Print() {
				System.out.println("Anonymous_Normal called");
				super.Print();
			}
		};
		Anonymous_Normal.Print();
	}
	public void CalledInterfaceDemoPrint() {
		InterfaceDemo Anonymous_Interface=new InterfaceDemo() {

			@Override
			public void Print(){
				System.out.println("Anonymous_Interface called");
			}
		};
		Anonymous_Interface.Print();
	}
	public static void main(String[] args)
	{		
		HelloWorld t=new HelloWorld();
		t.CalledAbstractClassPrint();
		t.CalledNormalClassPrint();
		t.CalledInterfaceDemoPrint();
		
	} 
}


InterfaceDemo.java

package my;

public interface InterfaceDemo
{
	public void Print();
}


NormalClass.java

package my;

public class NormalClass
{
	private int data=10;
	public void Print() {
		System.out.println("The value of NormalClass is "+data);
	}
	
}
執行結果: