一.内部类
外部类.内部类 对象 = new 外部类().new 内部类();
class Out {
class In {
public void print(){
System.out.println("这是内部类的一个方法");
}
}
}
public class Test {
public static void main(String[] args) {
Out.In in = new Out() . new In();
in.print();
}
}
运行结果:
这是内部类的一个方法
如果想让内部类只能被外部类调用,那么可以将内部类使用private进行封装
class Out {
private class In {
public void print(){
System.out.println("这是内部类的一个方法");
}
}
}
public class Test {
public static void main(String[] args) {
Out.In in = new Out() . new In();
in.print();
}
}
这样就无法通过之前的方法访问内部类了
内部类访问外部属性,要使用外部类.this.属性
不能直接使用this,因为内部属性中不存在num变量
class Out {
int num = 5;
class In {
public void print(){
System.out.println(Out.this.num);
}
}
}
public class Test {
public static void main(String[] args) {
Out.In in = new Out() . new In();
in.print();
}
}
外部类访问内部属性
class Out {
class In {
int num = 5;
public void print(){
System.out.println(this.num);
}
}
public void show(){
new In().print();
}
}
public class Test {
public static void main(String[] args) {
Out out = new Out();
out.show();
}
}
二.使用static定义内部类
当使用static修饰内部类以后,内部类也会变成使用外部类直接调用的形式,类似于static类型的变量和方法外部类.内部类 对象 = new 外部类.内部类();
class Out {
static class In {
public void print(){
System.out.println("这是内部类的一个方法");
}
}
}
public class Test {
public static void main(String[] args) {
Out.In in = new Out . In();
in.print();
}
}
同理,static修饰的类同样只能访问static修饰的变量或者方法
class Out {
int num = 5;
static class In {
public void print(){
System.out.println(num);
}
}
}
public class Test {
public static void main(String[] args) {
Out.In in = new Out . In();
in.print();
}
}
编译以后提示无法从静态上下文中引用非静态 变量 num,更改为
class Out {
static int num = 5;
static class In {
public void print(){
System.out.println(num);
}
}
}
public class Test {
public static void main(String[] args) {
Out.In in = new Out . In();
in.print();
}
}
正常运行
三.在方法中定义内部类
在JDK 1.7(包括1.7)之前,如果在方法中定义内部类之后,想要内部类直接访问方法的参数或者变量,那么需要在变量前加上final声明,在JDK 1.8之后则可以直接进行访问
class Out {
public void fun(final int a){
final int b = 2;
class In {
public void print(){
System.out.println(a + b);
}
}
new In().print();
}
}
public class Test {
public static void main(String[] args) {
Out out = new Out();
out.fun(1);
}
}
输出结果为3