如果你不不需要内部类与外部类之间的联系,可以将内部类生命为static的,这就是嵌套类。
注意:
1.要创建嵌套类的对象,并不需要外部类的对象。
2.不能从嵌套类对象中访问非静态的外部类对象。
嵌套类与普通类的区别:
1.普通类不能包含static数据和static属性,也不能包含嵌套类
2.
public class Parcel10 {
private static class ParcelContents implements Contents {
private int i = 11;
public int value() {
return i;
}
}
protected static class ParcelDestination implements Destination {
private String label;
private ParcelDestination(String str) {
this.label = str;
}
public String readLabel() {
return label;
}
public static void f() { }
static int x = 10;
static class AnotherLevel {
public static void f () {
}
static int x = 10;
}
}
public static Contents count() {
return new ParcelContents();
}
public static Destination dest(String s) {
return new ParcelDestination(s);
}
public static void main(String[] args) {
Contents c = count();
Destination d = dest("hello");
}
}
上代码:创建内部类对象时候不需要创建外部类对象。
1.嵌套类可以做为接口的一部分,并不会报错
interface A {
static class Inner {
int i;
public Inner() {}
void f(){}
}
}
interface A {
class Inner {
int i;
public Inner() {}
void f(){}
}
}
当然这样也不报错。。
注意:
1.要创建嵌套类的对象,并不需要外部类的对象。
2.不能从嵌套类对象中访问非静态的外部类对象。
嵌套类与普通类的区别:
1.普通类不能包含static数据和static属性,也不能包含嵌套类
2.
public class Parcel10 {
private static class ParcelContents implements Contents {
private int i = 11;
public int value() {
return i;
}
}
protected static class ParcelDestination implements Destination {
private String label;
private ParcelDestination(String str) {
this.label = str;
}
public String readLabel() {
return label;
}
public static void f() { }
static int x = 10;
static class AnotherLevel {
public static void f () {
}
static int x = 10;
}
}
public static Contents count() {
return new ParcelContents();
}
public static Destination dest(String s) {
return new ParcelDestination(s);
}
public static void main(String[] args) {
Contents c = count();
Destination d = dest("hello");
}
}
上代码:创建内部类对象时候不需要创建外部类对象。
1.嵌套类可以做为接口的一部分,并不会报错
interface A {
static class Inner {
int i;
public Inner() {}
void f(){}
}
}
interface A {
class Inner {
int i;
public Inner() {}
void f(){}
}
}
当然这样也不报错。。