- 匿名内部类就是内部类的间写格式
new 父类或者接口(){ 定义子类对象 } - 前提:
内部类必须继承一个类或一个接口。
abstract class AbsDemo{
abstract void show();
}
class Outer{
int x = 3;
/*将一下代码简化为匿名内部类 蓝色部分为使用匿名对象方法之前的写法!
class Inner extends AbsDemo{
void show(){
System.out.println("show :" +x);
}
}
*/
public void function(){
//new Inner().method();
//重点:
new AbsDemo(){ //匿名内部类,没名字,一般只调用一次!
void show(){
System.out.println("show :" +x);
}
}.show(); //点号前面的是一个AbsDemo的匿名子类对象。
}
}
class InnerClassDemo4{
public static void main(String[] args){
new Outer().function();
}
}
- 匿名内部类就是一个字类对象,只是这个对象有点胖,且只能使用一次!
- 用匿名对像的目的: 就是为了简化书写,覆盖(复写)方法。
- 方法太多不适合用匿名类,会降低代码可读性。一般方法不要超过三个。
练习:补全代码
interface Inter{
void method();
}
class Test{
/* 下面是内部类,但不是匿名内部类。
staticclass Inner implements Inter{
public void method(){
System.out.println("method : ");
}
}
static Inner function(){
Inner i1 = new Inner();
return i1;
}
*/
//补足代码,通过匿名内部类。
static Inter function(){
return new Inter(){ //匿名内部类,返回Inter类型的对象。
public void method(){
System.out.println("method : ");
}
};
}
}
class InnerClassDemo5{
public static void main(String[] args){
//理解:
//Test.function():Test类中有一个静态的方法function。
//.method():function()这个方法执行后的结果是一个对象,而且是一个Inter类型的对象。
//因为只有Inter类型的对象,才可以调用method方法。
Test.function().method();
}
}
- 常用情景:
interface Inter{
void method();
}
class Test{
/* 下面是内部类,但不是匿名内部类。
staticclass Inner implements Inter{
public void method(){
System.out.println("method : ");
}
}
static Inner function(){
Inner i1 = new Inner();
return i1;
}
*/
//补足代码,通过匿名内部类。
static Inter function(){
return new Inter(){ //匿名内部类,返回Inter类型的对象。
public void method(){
System.out.println("method : ");
}
};
}
}
class InnerClassDemo5{
public static void main(String[] args){
//理解:
//Test.function():Test类中有一个静态的方法function。
//.method():function()这个方法执行后的结果是一个对象,而且是一个Inter类型的对象。
//因为只有Inter类型的对象,才可以调用method方法。
Test.function().method();
//常用场景
show(new Inter(){
public void method(){
System.out.println("method show run ");
}
}); //注意这个分号不要省略。
}
public void static show(Inter in){
in.method();
}
}
- 面试题:
网友评论