【Java基础】内部类

一.内部类

外部类.内部类 对象 = 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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值