服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Java中的内部类使用详情

Java中的内部类使用详情

2022-09-15 17:24wx60d4764eb475e Java教程

说起内部类这个词,想必很多人都不陌生,但是又会觉得不熟悉。原因是平时编写代码时可能用到的场景不多,用得最多的是在有事件监听的情况下,并且即使用到也很少去总结内部类的用法。今天我们就来一探究竟

一,内部类访问成员

  • 1,内部类可以直接访问外部类的成员,包括私有。
  • 2,外部类要访问内部类,必须建立内部类对象。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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,直接访问内部类的中的成员

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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();
}
}

到此这篇关于Java十分钟精通内部类的使用的文章就介绍到这了,更多相关Java 内部类内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.51cto.com/u_15283585/5154338

延伸 · 阅读

精彩推荐