欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入
运行结果:
调用Outer构造方法:outer
调用Inner构造方法:inner
>>>>>Inner class! Outer class! 11 ——-1——–
调用Inner构造方法:inner
>>>>>Inner class! Outer class! 1001 ——-2——– 12 Process finished with exit code 0
二、内部类与接口
1、内部类可以实现接口。
2、内部类之间相互可见,但并非内部类之间方法都可见。
public interface Foo{
void say();
}
public interface Bar {
void readme();
}
/**
* 内部类实现接口
*
* @author leizhimin 2009-7-17 14:57:50
*/
public class Test2 {
public static void main(String[] args) {
Outer outer = new Outer();
Foo f = outer.genFoo();
Bar b = outer.genBar();
f.say();
b.readme();
}
}
class Outer {
private class FooImpl implements Foo {
public void say() {
System.out.println(“say foo!”);
}
}
private class BarImpl implements Bar {
public void readme() {
System.out.println(“say bar!”);
}
}
public Foo genFoo() {
return new FooImpl();
}
public Bar genBar() {
return new BarImpl();
}
}
输入结果:
say foo!
say bar!
Process finished with exit code 0
三、访问权限
外部类分两种:
一种嵌入了内部类声明代码外部类,称为直接外部类。 另一种是与内部类没有任何关系的外部类,称为外部类。
在同一个直接外部类中,内部类之间所有的方法都是相互可见的,包含在直接外部类的main()中可见。
在外部类中,要看到一个类的内部类成员,则至少要求这个内部类的class和成员权限大于或等于protected。
/**
* 内部类实现接口
*
* @author leizhimin 2009-7-17 14:57:50
*/
public class Test2 {
public static void main(String[] args) {
Outer o = new Outer();
Outer.Bar b = o.genBar();
b.readme();
}
}
class Outer {
protected class Foo {
protected void say() {
System.out.println(“say foo!”);
}
private void test() {
System.out.println(“—-test——“);
}
}
protected class Bar {
protected void readme() {
System.out.println(“say bar!”);
new Foo().test();
}
}
public Foo genFoo() {
return new Foo();
}
public Bar genBar() {
return new Bar();
}
}
[1][2]
要么读书、要么旅行,灵魂和身体,必须有一个在路上。