在一个类中再创建一个类就是内部类。内部类分有名内部类和匿名内部类。
1.对于有名内部类完全可以把它类比为为某个类中的一个方法因为它跟普通方法都有固定的格式。使用有名内部类就跟使用类中的一个普通函数一样,先创建外部类的对象,然后用外部类对象去调用内部类创建对象。(静态内部类暂时不包含)
public class Animal {//这是外部类
public void eat() {
System.out.println("杂食性动物");
}
public class Tigger{//这是一个内部类
public void eat() {
System.out.println("老虎是肉食性动物");
}
}
public static void main(String[] args) {
Animal animal = new Animal();
Tigger tigger = animal.new Tigger();
animal.eat();
tigger.eat();
}
}
2 匿名内部类(暂不包含静态的)(匿名内部类可以类比为成员变量)
2.1 对于普通类而言,普通类的匿名内部类是普通类的子类。用new 父类构造方法() 创建匿名内部类的对象。(匿名内部类必须直接实例化)
public class TestForNormal {
Animal tigger = new Animal() {//Animal 类还是上个部分那个Animal 类
public void eat() {
System.out.println("老虎是肉食性动物");
}
};
public static void main(String[] args) {
TestForNormal testForNormal = new TestForNormal();
testForNormal.tigger.eat();
}
}
2.2对于抽象类的匿名内部类来说,它是抽象类的子类,它必须实现抽象类的所有抽象方法,因为匿名内部类不能是抽象类
public abstract class Sea {
public abstract void pacific();
}
public class TestForAbstract {
Sea pacific = new Sea() {
@Override
public void pacific() {
System.out.println("这里是太平洋");
}
};
public static void main(String[] args) {
TestForAbstract testForAbstract = new TestForAbstract();
testForAbstract.pacific.pacific();
}
}
2.3对于接口来说,接口的内部类是它的实现类
public interface IGlobal {
public abstract void land();
}
public class TestForInterface {
IGlobal global = new IGlobal() {
@Override
public void land() {
System.out.println("这里是亚洲");
}
};
public static void main(String[] args) {
TestForInterface testForInterface = new TestForInterface();
testForInterface.global.land();
}
}
3.对于静态内部类来说,可以把它类比为静态的成员变量或者方法
3.1静态有名内部类
public class Animal {//这是外部类
public void eat() {
System.out.println("杂食性动物");
}
public static class Tigger{//这是一个内部类
public void eat() {
System.out.println("老虎是肉食性动物");
}
}
public static void main(String[] args) {
//Animal animal = new Animal();
//Tigger tigger = animal.new Tigger();
Tigger tigger = new Animal.Tigger();
//animal.eat();
tigger.eat();
}
}
3.2普通类的静态匿名内部类
public class TestForNormal {
static Animal tigger = new Animal() {
public void eat() {
System.out.println("老虎是肉食性动物");
}
};
public static void main(String[] args) {
//TestForNormal testForNormal = new TestForNormal();
//testForNormal.tigger.eat();
TestForNormal.tigger.eat();
}
}
3.3抽象类的静态匿名内部类
public class TestForAbstract {
static Sea pacific = new Sea() {
@Override
public void pacific() {
System.out.println("这里是太平洋");
}
};
public static void main(String[] args) {
//TestForAbstract testForAbstract = new TestForAbstract();
//testForAbstract.pacific.pacific();
TestForAbstract.pacific.pacific();
}
}
3.4接口的静态匿名内部类
public class TestForInterface {
static IGlobal global = new IGlobal() {
@Override
public void land() {
System.out.println("这里是亚洲");
}
};
public static void main(String[] args) {
//TestForInterface testForInterface = new TestForInterface();
//testForInterface.global.land();
TestForInterface.global.land();
}
}