【发布时间】:2021-09-16 19:00:15
【问题描述】:
要调用内部类的函数,我只需要一个内部类的对象。但是如果我已经创建了对象,为什么我不能在任何我想要的地方调用内部类的方法?试图暗示的错误是什么?
class Outer
{
int x;
class Inner // creating an Inner class
{
public void display()
{
System.out.println("Hello from Inner class"+x);
}
}
Inner i = new Inner();
i.display(); // This is where the error comes. Why do I have to create a method to call
// methods of my inner class. Why Can't I call it anywhere I want?
}
public class Main
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
【问题讨论】:
-
什么时候你希望
i.display()运行?! -
将
Inner i = new Inner(); i.display();移动到main -
既然您了解您需要创建一个方法或一个块,您已经知道如何解决您的问题。那么实际的问题是什么?
-
我知道如何修复它,我也知道我不能调用或使用那行代码,除非我把它移到一个方法中。但我知道这是因为我有大脑,而编译器没有。那么为什么编译器会拒绝这段代码呢?
-
@nSack 出于同样的原因,编译器将拒绝 public void doInt(int a) -> doInt("clearly not a primitive")。它检查您的代码是否有效。如果不是,则无法编译。
标签: java class oop inner-classes