日期:2014-05-20  浏览次数:20614 次

内部类这一块遇到问题啦
[code=Java]
[/package test4_bibao;

public class Programmer
{
private String name;
public Programmer(){}
public Programmer(String name)
{
this.name=name;
}
/**
* @return the name
*/
public String getName()
{
return name;
}
/**
* @param name the name to set
*/
public void setName(String name)
{
this.name = name;
}
public void work()
{
System.out.println(name+"编程");
}
}
]

[code=Java]
[/
package test4_bibao;

interface Teachable
{
void work();
}
]

[code=Java]
[/
package test4_bibao;

public class TeachableProgrammer extends Programmer
{
public TeachableProgrammer()
{
}

public TeachableProgrammer(String name)
{
super (name);
}

private void teach()
{
System.out.println("教师讲课"+getName());
}

private class Closure implements Teachable
{
public void work()
{
teach();
}
}

public Closure getCallbackReference()
{
return new Closure();
}

}
]
[code=Java]
[/
package test4_bibao;

public class TestTeachableProgrammer
{

/**
* @param args
*/
public static void main(String[] args)
{
TeachableProgrammer tp=new TeachableProgrammer("李刚");
tp.work();
tp.getCallbackReference().work();
}

}
]
最后这个文件时一个可运行文件,但是在运行最后一条语句的时候出现错误!~~
不知道是什么原因啊,希望高手解答

------解决方案--------------------
Closure是private的啊,怎么可以直接调用呢?
强制转换一下((Teachable)tp.getCallbackReference()).work(); 
或者:把函数的返回类型改一下,改成 
Teachable getCallbackReference() 

return new Closure(); 
}
------解决方案--------------------
很简单,因为private class Closure implements Teachable 你设置的是有的,在外部是不可见的。
设置成public就OK了