内部类

内部类:静态内部类、非静态内部类、匿名内部类

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;
	}
}

 

转载于:https://my.oschina.net/u/3544285/blog/1204688

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值