Java中的小问题1

来源:互联网 发布:网络筛子赌博技巧 编辑:程序博客网 时间:2024/06/06 02:43
近来学习Java,联系书中小例子,突然出现了这么个问题

No enclosing instance of type xx is accessible. Must qualify the allocation with an enclosing instance of type xx.

错误原因:

因为xx是一个动态的内部类,创建这样的对象必须有实例与之对应,程序是在静态方法中直接调用动态内部类会报这样错误。

解决办法:
可以把该内部类声明为static或者不要在静态方法中调用。
eg:
public class test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

father f=new son();
f.print();
}
static class father
{
public void print()
{
System.out.println("这是父类的函数");
}
}
static class son extends father
{
public void print()
{
System.out.println("这是儿子的函数");
}
public void print1()
{
System.out.println("这是儿子的另一个函数");
}
}
}
该例子中,father f=new son();其将父类对象句柄指向了子类对象,实际上操作的还是子类对象。
如果主函数中使用f.print1();编译错误,没有结果!因为f是父类的数据类型,那么在父类中没有print1()方法,只有print()方法。又由于这个句柄指向子类对象,所以其职能操作子类中父类该父类的方法。
知识点:
        如果父类引用指向一个子类的对象,那么通过父类引用,只能调用父类所定义的允许继承的方法。如果子类重写了继承父类的方法,那么会调用子类中的方法。
原创粉丝点击