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 中 B b = new B() 会出错。