内部类
内部类的访问规则
1)内部类可以直接访问外部类
之所以可以直接访问外部类中的成员,是因为内部类中持有了一个外部类的引用,格式:外部类名.this
2)外部类要访问内部类,必须建立内部类对象
访问格式:
1)当内部类定义在外部类的成员位置上,而且非私有,可以在外部其他类中直接建立内部类对象
格式:
外部类名.内部类名 变量名 = 外部类对象.内部类对象;
Outer.Inner in = new Outer().new Inner();
代码如下:
public class InnerClassTest1 {
public static void main(String[] args) {
Outer.Inner inner = new Outer().new Inner();
inner.method();
}
}
class Outer{
private int num = 4;
class Inner{
private int num = 5;
void method(){
System.out.println(Outer.this.num);
}
}
void function(){
Inner inner = new Inner();
inner.method();
}
}
2)当内部类在成员位置上,就可以被成员修饰符所修饰
比如:private:将内部类在外部类中进行封装
static:内部类就布局static的特性
当内部类被static修饰后看,只能直接访问外部类中的static成员,出现了访问局限
在外部其他类中,如何直接访问static内部类的非静态成员呢?
new Outer.Inner().function();
在外部其他类中,如何直接访问static内部类的静态成员?
Outer.Inner.funtion();
注意:当内部类中定义了静态成员时,内部类必须被static修饰
当外部类中的静态方法访问内部类时,内部类必须是static的
代码如下:
public class InnerClassTest1 {
public static void main(String[] args) {
Outer.Inner inner = new Outer.Inner();
Outer.Inner.method();
}
}
class Outer{
private int num = 4;
static class Inner{
private int num = 5;
static void method(){
System.out.println("haha");
}
}
void function(){
Inner.method();
}
}
当描述事物时,事物的内部还有事物,该事物用内部类来描述。
因为内部事物在使用外部事物的内容
以人体和心为例:
class Body{
private class Heart{
}
void show(){
new Heart();
}
}
内部类定义在局部时:
1)不可以被成员修饰符修饰
2)可以直接访问外部类中的成员,因为还持有内部类的引用
但是不可以访问它所在的局部中的变量,只能访问被final修饰的局部变量
代码如下:
class Outer{
private int num = 4;
void function(final int x){
class Inner{
void method(){
System.out.println(x);
System.out.println(Outer.this.num);
}
}
new Inner().method();
}
}
匿名内部类
1)匿名内部类其实就是内部类的简写格式
2)定义匿名内部类的前提
内部类必须是继承一个类或者实现接口
3)匿名内部类的格式:
new 父类或者接口(){定义子类的内容}
4)其实匿名内部类就是一个匿名子类对象,带内容的对象。
5)匿名内部类中的方法定义最后不要超过3个,否则阅读性不好
代码如下:
public static void main(String[] args) {
Comparator<String> comp = new Comparator<String>(){
public int compare(String s1, String s2) {
return s1.length()-s2.length();
}
public void show(){
System.out.println("haha");
}
};
System.out.println(comp.compare("haha", "hey"));
//comp.show(); //编译失败
}
interface Inter{
void method();
}
class Test{
//匿名内部类完成
}
Test.function().method();
用内部类完成代码如下:
interface Inter{
void method();
}
class Test{
static class SubInter implements Inter{
public void method(){
}
}
public static Inter function(){
SubInter inter = new SubInter();
return inter;
}
}
interface Inter{
void method();
}
class Test{
public static Inter function(){
return new Inter(){
public void method(){
}
};
}
}