简体   繁体   中英

How can I use a local variable to use a method from another class in BlueJ?

Basically I have two classes Country and City. In city I have a method called getSize. I want to use this method in the Country class so I tried using this:

City c = City.getSize(); 

To store the method as a local variable but I either get an error about incompatible types or static methods?

can you show the error?

And why don't you create

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

You should do this if your method getSize is not static:

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

And if the method is static then you can directly use it with the class name:

int size = City.getSize();

But I think you require first one as all city instance will have different size.

For the question : To store the method as a local variable

Answer : You cannot do such thing in java. You should first create an instance of the class and then you can call the method using that instance any number of time you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM