在Java中,构成代码的单元是类。每一个类都有自己的属性和方法,而在Java的语法中,允许类中再定义类。下面总结下Java内部类的使用方法。
首先,要说明的是,内部类可以访问外部类的成员和方法,但是外部类不能直接访问内部类。内部类的使用,是附加在外部类的对象上的。
内部类分为非静态内部类,静态内部类,和匿名类三种。
1)非静态内部类
class Outer{
int type;
String s = "Hello";
class InnerOne{
void f1(){
String type;
System.out.println(Outer.this.type);
System.out.println(this.type);
System.out.println(s);
}
}
static class InnerTow{
void f2(){
System.out.println(type);
}
}
需要注意的是,非static类不可以定义static方法,因为static属于类本身,而static方法属于类,非静态内部类是属于外部类的,所以方法不可以定义成static。
但若是static内部类,外部类的变量时不可以被访问的
转发至微博
转发至微博