java内部类笔记

为什么需要内部类:每个内部类都能独立的继承自一个接口,所以无论外围类是否继承某个接口的实现,对内部类都没有影响。内部类使多重继承的解决方案变得完整。
定义在方法中的内部类
interface first{
public void A();
public void B();
}
public class sixth {
public first fir14(String s){
class Inner implements first{
public void A(){}
public void B(){}
}
return new Inner();
}
在类内部的方法里面创建类实现外部接口。返回向上转型以后基类的引用。也可以在方法内部的作用域里面嵌入内部类如for while等。
实现匿名类的内部类:
public class parc16{
public Contents cont(){
return new  Contents(){
private int i=1;
public int value(){return i;//return super.value();}
};
}
public static void main(String[] args){
parce16 p= new parce16();
Contents c= p.cont();
}
}
创建一个继承自Contents的一个匿名内部类的对象,通过new自动向上转型为Contents。记得return后面的";"。
java的回调机制:
package second;


import javax.sound.midi.VoiceStatus;
import javax.swing.table.TableStringConverter;


import org.ietf.jgss.Oid;


interface Incermentable{void increment();}
class Calleel implements Incermentable{
private int i=0;
public void increment(){
i++;
System.out.println("callee1   "+i);
}
}
class Myincrement{
void increment(){
System.out.println("other operation");
}
static void f(Myincrement myincrement){myincrement.increment();}
}
class Callee2 extends Myincrement{
private int i=0;
private void incr(){
i++;
System.out.println("callee2   "+i);
}
private class Closurse implements Incermentable{
public void increment(){incr();}
}
Incermentable getCallbackReference(){
return new Closurse();
}
}
class Caller{
private Incermentable callbackreference;
Caller(Incermentable cbh){callbackreference=cbh;}
void go(){callbackreference.increment();}
}
public class CallBack {
public static void main(String[] args){
Calleel c1=new Calleel();
Callee2 c2=new Callee2();
Myincrement.f(c2);
Caller caller1=new Caller(c1);
Caller caller2=new Caller(c2.getCallbackReference());
caller1.go();
caller1.go();
caller2.go();
caller2.go();
}


}
输出:
other operation
callee1   1
callee1   2
callee2   1
callee2   2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值