[转]JAVA 在main中访问内部类、方法等

时间:2023-03-08 21:17:06
[转]JAVA 在main中访问内部类、方法等

1.使用静态的属性、方法、内部类

 class A
{
static int i = 1; // A 类的静态属性
static void outPut() // A 类的静态方法
{
System.out.println(i);
}
static class B // A 类的静态内部类
{
void outPut()
{
System.out.println("B");
}
}
public static void main(String[] args)
{ System.out.println(i); // 调用静态的属性
outPut(); // 调用静态的方法
B b = new B(); // 调用静态的内部类
b.outPut();
}
}

2.使用此类的对象名访问

 class A
{
int i = 1; // 属性
void outPut() // 方法
{
System.out.println(i);
}
class B // 内部类
{
void outPut()
{
System.out.println("B");
}
}
B newB() // (关键)在动态方法中建立 B 的对象
{
B b = new B();
return b;
}
public static void main(String[] args)
{
A a = new A();
System.out.println(a.i); // 调用属性
a.outPut(); // 调用方法
B b = a.newB(); // 调用内部类
b.outPut();
}
}

在静态的main中,无法创建非静态的内部类。