题目:
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();
}
}