内部类:静态内部类、非静态内部类、匿名内部类
public class Animal {
String name = "animal";
static int age = 10;
class Dog {
int price = 100;
String name = "dog";
//static int ageDog = 10;非静态内部类中不能有静态方法和属性
public void run() {
System.out.println("age=" + Animal.age + ",name" + Animal.this.name + name);
}
}
static class Cat{//静态内部类只能调用外部类的静态属性和方法
static String name = "cat";
}
public void move() {
Dog dog = new Dog();
dog.run();
}
}
class Test {
public static void main(String[] args) {
Animal animal = new Animal();
animal.move();
Animal.Dog dog = new Animal().new Dog();//new内部类写法
Animal.Cat cat = new Animal.Cat();//new静态内部类
}
}
匿名类:匿名内部类只能使用一次,通常来简化代码编写
前提 :必须继承父类或实现一个接口
例子;
public interface Fly {//接口中的匿名内部类
public void move() {
}
}
class Bird implements Fly {
public static void main(String[] args) {
Bird bird = new Bird() {
public void move() {
System.out.println("飞过去");
}
}
bird.move;
}
}