如何使用局部变量来使用BlueJ中另一个类的方法?

时间:2012-11-28 13:36:55

标签: java class variables methods local

基本上我有两个国家和城市类。在城市我有一个名为getSize的方法。我想在Country类中使用此方法,所以我尝试使用它:

City c = City.getSize(); 

要将方法存储为局部变量,但我收到有关不兼容类型或静态方法的错误?

2 个答案:

答案 0 :(得分:2)

你可以显示错误吗?

为什么不创建

City c = new City(); 
int size = c.getSize();

答案 1 :(得分:1)

如果您的方法getSize不是静态的,那么您应该这样做:

City c = new City();
int size = c.getSize(); // use the returned value (assuming it is returning an integer)

如果方法是静态的,那么你可以直接将它与类名一起使用:

int size = City.getSize();

但我认为你需要第一个,因为所有城市实例都有不同的大小。

问题:To store the method as a local variable

答:你不能在java中做这样的事情。您应该首先创建该类的实例,然后您可以使用该实例调用该方法任意数量的时间。