内部类的访问规则:(内部类可以被私有化)
1.内部类可以直接访问外部类中的成员,包括私有。之所以可以直接访问外部类中的成员,是因为内部类中持有了一个外部类的引用,格式:外部类名.this
2.外部类要访问内部类,必须建立内部类对象。
格式:Outer.Inner in = new Outer().new Inner();
public static void main(String[] args) {
Outer out = new Outer();
out.method();
//直接访问内部类中的成员格式:
Outer.Inner in = new Outer().new Inner();
in.function();
}
}
class Outer{
int x = 3;
class Inner{//内部类
void function() {
System.out.println("inner :"+x);
}
}
void method() {
Inner in = new Inner();
in.function();
}
}
外部类访问内部类的方法,外部类方法中建立内部类对象。结果为:Inner:3
类中的成员访问方式:
public static void main(String[] args) {
Outer out = new Outer();
out.method();
}
}
class Outer{
int x = 3;
class Inner{//内部类
int x = 4;
void function() {
int x = 5;
System.out.println("inner :"+Outer.this.x);//访问function中的x,直接+x,内部类中的x this.x,外部类中的x如上。
}
}
void method() {
Inner in = new Inner();
in.function();
}
}
注意:当内部类中定义了静态成员,该内部类必须是static的。
当外类中的static方法访问内部类时,内部类也必须是static的
匿名内部类:
1.匿名内部类其实就是内部类的简写。
2.定义匿名内部类的前提:内部类必须是继承一个类或者实现接口。
3.匿名内部类的格式:new 父类或者接口(){定义子类的内容}
4.其实匿名内部类就是一个匿名子类对象,而且这个对象有点胖,可以理解为带内容的对象。
5.匿名内部类中定义的方法最好不超过三个。
public static void main(String [] args) {
new Outer1().function();
}
}
class Outer1{
int x = 4;
/*
class Inner extends AbsDemo{
void show{
System.out.println("x="+x);
}
}
*/
public void function() {
//new Inner().show();
new AbsDemo() {
void show() {
System.out.println("x="+x);
}
}.show();
}
}
abstract class AbsDemo{
abstract void show();
}
练习:
public static void main(String [] args) {
Test.function().method();
Inter in = Test.function();
in.method();
//Test.function():Test类中有一个静态方法function
//function这个方法运算后是一个对象,而且是Inter类型的对象。
//因为只有是Inter类型的对象,才可以调用method方法。
}
}
class Test{
//通过匿名内部类补足代码
static Inter function() {
return new Inter() {
public void method(){
System.out.println("haha");
}
};
}
}
interface Inter{
void method();
}