1. 程式人生 > >Java匿名內部類的兩種經典用法

Java匿名內部類的兩種經典用法

匿名內部類是在單一表達式內定義的巢狀類。因為這些類沒有名稱和建構函式,所以稱為匿名類。它們只能訪問最終方法變數和引數。

class Inner
{
	public static void main(String[] args)
	{
		Bank b = new Bank();
		System.out.println(b.getCustomer().getName());
	}
}

class Bank
{
	Customer getCustomer()
	{
		return new Customer()
		{
			String getName()
			{
				return "Frank";
			}
		};
	}
}

abstract class Customer
{
	abstract String getName();
}

public interface Accountable
{
	public double getBalance();
	public void setBalance(double d);
}

public class AccountableAdapter implements Accountable
{
	public double getBalance()
	{
		return 0;
	}	
	public void setBalance(double d)
	{
	}
}

public class Customer
{
	AccountableAdapter aa = new AccountableAdapter()
	{
		public void setBalance(double d)
		{
			System.out.println("balance = "+d);
			super.setBalance(d);
		}
	};
}