黑马程序员技术交流社区
标题:
毕老师给出的一个很不错的问题,大家能不能帮解答一下?
[打印本页]
作者:
张慈瑞
时间:
2014-7-11 20:34
标题:
毕老师给出的一个很不错的问题,大家能不能帮解答一下?
interface Inter
{
void method();
}
class Test
{
//补足代码。通过匿名内部类。
}
class InnerClassTest
{
public static void main(String[] args)
{
Test.function().method();
}
}
作者:
hejinzhong
时间:
2014-7-11 21:02
本帖最后由 hejinzhong 于 2014-7-11 21:17 编辑
i
nterface Inter // 定义了一个接口Inter
{
void method();
}
class Test
{
public static Inter function
{
return new Inter()
{
这里自己覆写父类中method
};
}
}
class InnerClassTest
{
public static void main(String[] args)
{
Test.function().method();
}
}
分析:在主函数中(Test.function().method();)这句话可以看出,method()方法被调用,而method存在与Inter接口中,所以要使用该方法,必须建立他的子类才可以调用。所以Test.function()的运行结果是个Inter子类类型的类类型数据,而且直接通过Test类名调用了Test内部的function函数,所以function函数是static。
这样的话就可以写出:
class Test
{
static Inter的子类名 function()
{
return new inter的子类;//因为接口不能直接创建对象,只能有子类实现后才可以.
}
}
因为这里InnerClassTest 类的主函数只调用一次method,所以可以通过匿名内部类解决,简化代码.
怎么创建匿名内部类,你看看前面概念视频和格式就OK
作者:
玉遥
时间:
2014-7-11 21:04
<P>interface Inter {
void method();
}</P>
<P>class Test {
public static Inter function() {
return new Inter() {
public void method() {
System.out.println("匿名内部类");
}
};
}
}</P>
<P>class InnerClassTest {
public static void main(String[] args) {
Test.function().method();
// 类名直接调用,function是静态修饰的,而其又调用了接口中的method方法,说明function返回的是一个
// 接口的子实现类的对象,这里只能用匿名内部类实现方法。
}
}</P>
复制代码
作者:
215041631
时间:
2014-7-11 21:07
package niming;
class UnName
{
public static void main(String[] args)
{
Test.function().method();
}
}
interface Inter
{
void method();
}
class Test
{
static Inter function()
{
return new Inter()
{
public void method()
{
System.out.print("Inner");
}
};
}
}
作者:
EarlyHeart
时间:
2014-7-11 21:14
interface Inter {
void method();
}
class Test {
public static Inter function() {
return new Inter() {
public void method() {
}
};
}
}
class InnerClassTest {
public static void main(String[] args) {
Test.function().method();
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2