Java中的内部类使用详情
作者:wx60d4764eb475e 时间:2022-07-24 05:09:38
一,内部类访问成员
1,内部类可以直接访问外部类的成员,包括私有。
2,外部类要访问内部类,必须建立内部类对象。
class Outer
{
int x = 3;
class Inner{
void function(){
System.out.println("inner : " + x);
}
}
void method(){
Inner in = new Inner();
in.function();
}
}
class InnerClassDome
{
public static void main (String[] args)
{
Outer out = new Outer();
out.method();
}
}
二,访问内部类成员
1,直接访问内部类的中的成员
class Outer
{
int x = 3;
class Inner{
void function(){
System.out.println("inner : " + x);
}
}
void method(){
Inner in = new Inner();
in.function();
}
}
class InnerClassDome
{
public static void main (String[] args)
{
//Outer out = new Outer();
//out.method();
Outer.Inner in = new Outer().new Inner();
in.function();
}
}
2,访问成员
之所以可以直接访问外部类的成员,是因为内部类中持有了一个外部类的引用,格式: 外部类名.this
class Outer
{
int x = 3;
class Inner{
int x = 4;
void function(){
int x = 6;
System.out.println("inner : " + x);
System.out.println("inner : " + this.x);
System.out.println("inner : " + Outer.this.x);
}
}
void method(){
Inner in = new Inner();
in.function();
}
}
class InnerClassDome
{
public static void main (String[] args)
{
//Outer out = new Outer();
//out.method();
Outer.Inner in = new Outer().new Inner();
in.function();
}
}
来源:https://blog.51cto.com/u_15283585/5154338
标签:Java,内部类
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
springboot中使用redis并且执行调试lua脚本
2022-02-15 08:49:52
![](https://img.aspxhome.com/file/2023/1/61031_0s.png)
Android Rxjava3 使用场景详解
2023-08-06 08:58:50
![](https://img.aspxhome.com/file/2023/3/84723_0s.jpg)
Java实现人机猜拳小游戏
2023-10-07 16:11:37
![](https://img.aspxhome.com/file/2023/1/58681_0s.jpg)
Java 判断字符串中是否包含中文的实例详解
2023-11-06 13:17:18
![](https://img.aspxhome.com/file/2023/3/58913_0s.png)
详解Java目录操作与文件操作教程
2023-12-05 13:45:48
![](https://img.aspxhome.com/file/2023/7/58887_0s.png)
Java线程的全方位详解
2023-04-11 14:02:55
![](https://img.aspxhome.com/file/2023/2/61042_0s.png)
Spring整合MyBatis图示过程解析
2023-11-13 11:45:09
![](https://img.aspxhome.com/file/2023/8/59188_0s.png)
安卓GreenDao框架一些进阶用法整理
2023-06-17 03:27:21
Java调用接口如何获取json数据解析后保存到数据库
2023-11-16 15:01:36
![](https://img.aspxhome.com/file/2023/8/59058_0s.png)
java开发微信分享接口的步骤
2021-08-22 12:30:59
![](https://img.aspxhome.com/file/2023/2/61652_0s.png)
Kafka 日志存储实现过程
2021-11-01 05:04:00
![](https://img.aspxhome.com/file/2023/7/62337_0s.png)
简单探索 Java 中的惰性计算
2023-11-16 20:25:28
Java面试题之基本语法(图解)
2023-11-24 09:37:34
![](https://img.aspxhome.com/file/2023/5/59915_0s.png)
Mybatis Plus中的流式查询案例
2023-08-18 16:35:13
浅谈Java(SpringBoot)基于zookeeper的分布式锁实现
2023-11-16 08:14:56
关于Spring Data Jpa 自定义方法实现问题
2023-11-28 10:08:32
Springboot初始化项目并完成登入注册的全过程
2023-07-31 15:09:09
![](https://img.aspxhome.com/file/2023/8/57948_0s.png)
浅谈java中String StringBuffer StringBuilder的区别
2023-11-29 13:34:40
java实现短地址服务的方法(附代码)
2023-11-15 19:13:41
![](https://img.aspxhome.com/file/2023/5/59525_0s.png)
基于FeignException$InternalServerError的解决方案
2023-04-25 15:50:45
![](https://img.aspxhome.com/file/2023/2/60492_0s.png)