可以将一个类的定义放在另一个类的定义内部,这就是内部类。
一、创建内部类:
package 内部类.创建内部类;
public class Parcal2 {
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 void ship(String dest){
Contents c=new Contents();
Destination d=to(dest);
System.out.println(d.readLabel());
}
public Contents contents(){
return new Contents();
}
public static void main(String[] args) {
Parcal2 p1=new Parcal2();
p1.ship("abc");
Parcal2.Contents c= p1.contents();
Parcal2.Destination d=p1.to("123");
String a=d.readLabel();
System.out.println(a);
}
//具体指明对象类型:outcladdname.innerclassname
}
具体指明对象类型:outcladdname.innerclassname
二、内部类的继承
package 内部类.创建内部类;
public class Sequence {
private Object[] items;
private int next=0;
public Sequence(int size){
items=new Object[size];
}
public void add(Object x){
if(next<items.length) items[next++]=x;
}
private class SequenceSelectort implements Selector{
@Override
public boolean end() {
return false;
}
@Override
public Object current() {
return null;
}
@Override
public void next() {
}
}
}
三、使用.new
package 内部类.创建内部类;
public class Parcal2 {
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 void ship(String dest){
Contents c=new Contents();
Destination d=to(dest);
System.out.println(d.readLabel());
}
public Contents contents(){
return new Contents();
}
public static void main(String[] args) {
Parcal2 p1=new Parcal2();
p1.ship("abc");
Parcal2.Contents c= p1.contents();
Parcal2.Destination d=p1.to("123");
String a=d.readLabel();
System.out.println(a);
Parcal2.Contents c2=p2.new 内部类.创建内部类.Parcal2.Contents();
}
}