夜光序言:
一如既往,孤独相伴,万千纷扰,与我何干。
正文:内部类与匿名类
夜光:两个内部类实现不同接口的使用示例
匿名类
匿名类与内部类对照使用示例
class Outer { //定义一个外嵌类
private int index = 100;
int x=10;
class Inner { //定义一个内部类
private int index = 50;
void print() { //测试三个同名变量index的访问方式
int index = 30;
System.out.println("局部变量:"+index); // index= 30
System.out.println("内部类的成员变量:"+this.index); // index=50
System.out.println("外嵌类的成员变量:"+Outer.this.index+" x="+x); // index=100
}
}
Inner getInner() { // 在外嵌类中创建内部类的对象
return new Inner();
}
}
public class TestInner{ //定义一个测试类
public static void main(String[] args) {
Outer outer = new Outer(); // 创建一个外嵌类的对象
Outer.Inner inner = outer.new Inner(); // 创建一个类的内部类的对象
inner.print();
}
}
/内部类使用示例
public class TestInnerOne
{
private class Content implements Contents //实现接口1的内部类1
{
private int i = 11;
public int value() //实现接口1的方法
{
return i;
}
}
protected class GDestination implements Destination //实现接口2的内部类2
{
private String label;
private GDestination(String whereTo) //构造函数
{
label = whereTo;
}
public String readLabel() //实现接口2的方法
{
return label;
}
}
public Contents cont() //外嵌类的方法1,返回一个接口1的对象
{
return new Content(); //构造内部类1的对象
}
public Destination dest(String s) //外嵌类的方法2,返回一个接口2的对象
{
return new GDestination(s); //构造内部类2的对象
}
public interface Contents //接口1
{
int value(); //接口1的方法
}
public interface Destination //接口2
{
String readLabel(); //接口2的方法
}
public static void main(String[] args)
{
TestInnerOne p = new TestInnerOne(); //构造外嵌类的对象
Contents c = p.cont(); //通过外嵌类的方法1来构造一个内部类1的对象
Destination d = p.dest("Beijing"); //通过外嵌类的方法2来构造一个内部类2的对象
System.out.println(d.readLabel()+" | "+c.value()); //调用两个内部类的方法
}
}
abstract class Hello { // 抽象类
abstract void sayHello();
}
//用匿名类,做方法的参数
class TestNoNameInner1 {
public static void main(String[] args) {
new TestNoNameInner().callInner(
new Hello() { // 用匿名类,做方法的参数
public void sayHello() {
System.out.println("Hello!哈哈");
}
}
);
}
public void callInner(Hello a) {
a.sayHello();
}
}
//用内部类,在方法中
class TestNoNameInner2 {
public static void main(String[] args) {
class Inner extends Hello { // 用内部类,在方法中
public void sayHello() {
System.out.println("Hello!哈哈");
}
}
new TestNoNameInner().callInner(new Inner());
}
public void callInner(Hello a) {
a.sayHello();
}
}