Java 简述匿名内部类的江湖

摘自Thinking  in Java 第四版

思考:Anonymous Inner Class(匿名内部类)是否可以继承其它类?是否可以实现接口? 

答案:匿名内部类与正规的继承相比有些受限,因为匿名内部类既可以继承类,也可以实现接口,但是不能两者兼备,实现接口也只能实现一个。


举例说明什么是匿名内部类:


class OuterMyTest {

public Test getFun(){
return new Test(){
private int  i = 1;
public int value() {
return i;
}
};

}


public static void main(String[] args) {
OuterMyTest aTest = new OuterMyTest();
Test test =  aTest.getFun();

}
}


class Test {
void getFun(){
System.out.println("Test.getFun()");
}
}


getFun方法将返回值的生成与表示这个返回值的类的定义结合在一起,

这个类是匿名的,没有名字的。

创建一个继承自Test的匿名类的对象,通过new表达式返回的引用被自动向上转型为对Test的引用。


如果带参数 怎么办?


class OuterMyTest {

public Test getFun(int j){
return new Test(j){
private int  i = 1;
public int value() {
return i;
}
};
}



public static void main(String[] args) {
OuterMyTest aTest = new OuterMyTest();
Test test =  aTest.getFun(0);

}
}


class Test {
public Test(int j) {
System.out.println("Test.Test");
}


void getFun(){
System.out.println("Test.getFun()");
}
}


如果是:


class OuterMyTest {

public Test getFun(int j){
return new Test(){
private int  i = j;
public int value() {
return i;
}
};
}


public static void main(String[] args) {
OuterMyTest aTest = new OuterMyTest();
Test test =  aTest.getFun(0);

}
}


class Test {
public Test(int j) {
System.out.println("Test.Test(int j)");
}


public Test() {
System.out.println("Test.Test()");
}


void getFun(){
System.out.println("Test.getFun()");
}
}


编译报错:Cannot refer to the non-final local variable j defined in an enclosing scope


如果定义一个匿名内部类,并且希望它使用一个在其外部定义的对象,那么编译器要求其参数引用是final的。


如果被传递给匿名类的基类的构造器,它并不会在匿名类内部被直接使用,则不要求j是final的,

如果在匿名类内部使用,就要求j是final的


class OuterMyTest {

public Test getFun( final String dest,final float price){
return new Test(){
private int  cost;
{
cost = Math.round(price);
if(cost>100){
System.out.println(cost);
}
}
private String lable = dest;
public String readLable() {
return lable;
}
};
}


public static void main(String[] args) {
OuterMyTest aTest = new OuterMyTest();
Test test =  aTest.getFun("china", 109.12F);

}
}


class Test {
public Test(int j) {
System.out.println("Test.Test(int j)");
}


public Test() {
System.out.println("Test.Test()");
}
}





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值