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);
		}
	};
}


你可能感兴趣的:(Java)