java关于内部类的巧妙使用(一道经典面试题)

题目:
interface Inter{

void show();

}

class Outer{

//补齐代码,使得主函数输出hello world

}

public class Mianshi {

public static void main(String[] args) {

	Outer.method().show();

}

}
注:接口以及有主函数的类不能改变。

方法一(不通过内部类实现):
【由题,通过Outer.method().show();实现输出。
但是Outer并没有通过new Outer,说明Outer中的method方法是一个类方法(通过类可直接调用);
同时,调用方法后还能接着调用show()方法,说明method()是有返回值的,并且返回值并不是普通的如int、boolean等类型,而是类或者接口,方便可以继续调用其中方法的返回类型。
同时,可以看到show方法是在接口中,如果要通过Outer.method().show();实现输出hello world,则要实现该接口中的show()方法,然后才能被method()方法调用。】

interface Inter{
void show();
}

class A implements Inter(){
@Override
public void show(){
System.out.println(" hello world");
}
}//通过类A来实现接口中的show方法

class Outer{
public static A method(){

return new A();//method为静态方法,返回A类型
}

}

public class Mianshi {
public static void main(String[] args) {
Outer.method().show();//相当于A.show();
}
}

方法二(通过内部类实现):
interface Inter{
void show();
}

class Outer{
public static Inter method(){

return new Inter(){
@Override
public void show(){
System.out.println(" hello world");
}; //直接通过内部匿名类来实现接口,返回的是实现了的Inter接口(花括号{ }中整个一部分用于实现接口,注意结尾一定要用分号结束,相当于一个完整的语句)
}

}

public class Mianshi {
public static void main(String[] args) {
Outer.method().show();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值