软件编程
位置:首页>> 软件编程>> java编程>> Java中的内部类使用详情

Java中的内部类使用详情

作者:wx60d4764eb475e  发布时间:2022-07-24 05:09:38 

标签:Java,内部类

一,内部类访问成员

  • 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

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com