java 内部类

内部类:在另一个类的内部定义的类叫做内部类。

例1:

public class Parcell 

{
class Contents
{
private int i = 11 ;
public int value()
{
return i ;
}
}

class Destination
{
private String label ;
Destination(String whereTo)
{
label = whereTo ;
}

String readLabel()
{
return label ;
}
}

public void ship(String dest)
{
Contents c = new Contents();
Destination d = new Destination(dest) ;

System.out.println(c.value());
System.out.println(d.readLabel());
}

public static void main(String[] args)
{
Parcell p = new Parcell();
p.ship("tanzania");
}

}

在ship中使用内部类时和其他类没有什么区别。典型的情况是:外部类会有一个方法,返回一个指向内部类的引用,如例2:

例2:

public class Parcell2 
{
class Contents
{
private int i = 11 ;
public int value()
{
return i ;
}
}

class Destination
{
private String label ;
Destination(String whereTo)
{
label = whereTo ;
}

String readLabel()
{
return label ;
}
}

public Destination to(String s)
{
return new Destination(s);
}

public Contents cont()
{
return new Contents();
}

public void ship(String dest)
{
Contents c = cont();

Destination d = to(dest);

System.out.println(d.readLabel());
}

public void func()
{
Contents c = new Contents();
}

public static void main(String args[])
{
Parcell2 p = new Parcell2();
p.ship("tanzania");
Parcell2 q = new Parcell2() ;
Parcell2.Contents c = q.cont();


Parcell2.Destination d = q.to("Borneo");
}
}

  

两个例子的不同点在于:如果你想从外部类的非静态方法之外的任意位置创建某个内部类的对象,那么你必须像例2中的main方法那样,具体的指明这个对象的类型:OuterClassName.InnerClassName。

普通内部类和嵌套类的区别:

1、要创建嵌套类的对象,并不需要其外围类的对象;

2、不能从嵌套类的对象中访问非静态的外围类对象;

3、普通的内部类不能有static数据和static属性,也不能包含嵌套类,但是嵌套类可以。

java中不能多重继承,接口解决了部分问题,而内部类有效的实现了“多重继承”。

原文地址:https://www.cnblogs.com/peislin/p/2553524.html