Java点滴: Nested Class

[url=http://www.iteye.com/topic/442435]参考贴:内部类详解[/url]
tag: java,nested class

[b][size=large]Why do we need it?[/size][/b]

[list]
[*]It is a way of logically grouping classes that are only used in one place.
[*]It increases encapsulation.
[*]Nested classes can lead to more readable and maintainable code.
[/list]
[b][size=large]More scenario-sense[/size][/b]

[list]
[*]内部类提供了某种进入外围类的窗户。
[*]每个内部类都能独立地继承一个接口,而无论外围类是否已经继承了某个接口。
[/list]
因此,内部类使多重继承的解决方案变得更加完整。在项目中,需要多重继承,如果是两个接口,那么好办,接口支持多重继承。如果是两个类呢?这时只有使用内部类了。

[b][size=large]Sample[/size][/b]
public class NestedClassDemo {

private int _value = 1;
private static String _id = "1";

// 1. member class, defined in class
// inner class, scope: member
private class InnerA {
private int _value;
public InnerA(int value) {
_value = value;
}
public void readOuterA() {
// accessing outer class' member directly
System.out.println(_value);
}
public void readOuterB() {
// accessing outer class' member alternatively
System.out.println(NestedClassDemo.this._value);
}
}

public void foo() {
// 2. local class, defined in method, compiled with method
// inner class, scope: local (stack)
class InnerB {
public void show() {
System.out.println("NestedB defined in method");
}
}
// must be called afterwards
new InnerB().show();
}

public Object createAnonymous() {
final String temp = "anonymous";
// 3. anonymous inner class
// inner class, scope: point it is defined
return new Object() {
private int _value;
private String _id;
// initializer, using alternative way to resolve conflict
{
_value = NestedClassDemo.this._value;
_id = temp; // can only refer to final local variable
}
public String toString() {
return _id + _value;
}
};
}

// 4. nested static class, behaviors like a top-level class
// non-inner class, scope: (static) member
private static class Nested {
public void readOuter() {
// can access only static fields
System.out.println(_id);
}
}

public static void main(String[] args) {

NestedClassDemo nc = new NestedClassDemo();
// initialization: outerObj.new
NestedClassDemo.InnerA a = nc.new InnerA(nc._value);
// InnerA a = nc.new InnerA(); // is acceptable here
a.readOuterA();
a.readOuterB();

NestedClassDemo.Nested n = new NestedClassDemo.Nested();
// Nested n = new Nested(); // is acceptable here
n.readOuter();
}
}

public interface Service {
void serve();
}

public interface ServiceFactory {
Service getService();
}

public class ServiceImpl implements Service {
public void serve() {
// do something
}
public static ServiceFactory getService() {
return new ServiceFactory() {
public Service getService() {
return new ServiceImpl();
}
};
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值