首先展示的是普通多态的代码:
//定义接口
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 父类(参数列表)或 父类接口(){}中的这个花括号里面要写的是匿名子类的实现代码。
匿名内部类是实现接口的一种简便写法。匿名内部类是内部类的简写形式,
必须有前提:内部类必须继承或者实现一个外部类或者接口
匿名内部类其实就是一个匿名子类对象