匿名内部类的理解与使用

首先展示的是普通多态的代码:

//定义接口
interface Student{
	void eat();//定义抽象方法
}
class People implements Student{
public void eat() {
	System.out.println("学生要吃有营养的");
   }
}

public class Example01 {

	public static void main(String[] args) {
		Student student=new People();
		StudentEat(student);//调用StudentEat方法,student作为参数传入

	}
public static void StudentEat(Student student){
	student.eat();//调用传入对象an的eat方法
   }
}


在Java中为了实现多态,允许使用一个父类类型的变量来引用一个子类类型的对象,根据被引用子类对象特征的不同,得到不同的运行结果。由于我这个就是想说明匿名内部类如何实现接口,所以就只举了一个people的栗子。下面是使用内部类的栗子:


interface Student{
	void eat();//定义抽象方法
}
public class Example03 {

	public static void main(String[] args) {		
class People implements Student{
public void eat() {
	System.out.println("学生要吃有营养的");
   }
}
	StudentEat(student);//调用StudentEat方法,student作为参数传入
	}
public static void StudentEat(Student student){student.eat();//调用传入对象an的eat方法 }}接下来是使用了匿名内部类的栗子:
//定义接口
interface Student{
	void eat();//定义抽象方法
}
public class Example02 {

	public static void main(String[] args) {
		//定义匿名内部类作为参数传递给StudentEat()方法
    StudentEat(new People(){
    	//实现接口中的方法
	public void eat() {
		System.out.println("学生要吃有营养的");
	}
       });//这里要看仔细呀~
	}
	//定义一个静态方法
    public static void StudentEat(Student student){
    	student.eat();//调用传入对象an的eat方法
    }
}

那么我们分两步来理解内部类,首先:

在调用StudentEat()方法的时候,在参数位置上写你要实例化的对象,相当于创建了一个实例对象,并且会把这个对象的地址作为参数传给StudentEat()方法,在new People()后面有个{},这个是表示创建的People对象的子类实例,该子类是匿名的。一般是:new 父类(参数列表)或 父类接口(){}

其次,new 父类(参数列表)或 父类接口(){}中的这个花括号里面要写的是匿名子类的实现代码。

匿名内部类是实现接口的一种简便写法。匿名内部类是内部类的简写形式, 
必须有前提:内部类必须继承或者实现一个外部类或者接口 
匿名内部类其实就是一个匿名子类对象 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值