This site requires JavaScript, please enable it in your browser!
Greenfoot back
nx117
nx117 wrote ...

2018/10/21

Help

nx117 nx117

2018/10/21

#
How do you call a method from another class?
Alexlife2002003 Alexlife2002003

2018/10/21

#
MyWorld world = (MyWorld) getWorld();
world.endGame();
Alexlife2002003 Alexlife2002003

2018/10/21

#
Something like that ''MyWorld'' is the name of the class where your method is ''world'' is the new name you want to give it from where you are calling it after the'' = ''you just switch'' MyWorld ''to the name of your class. then at the second line, you switch ''world'' to whatever name you gave it and"endGame" to the method you want to call.
danpost danpost

2018/10/21

#
nx117 wrote...
How do you call a method from another class?
You really need to be more specific. Show the two classes involved and point to what you are trying to access and from where. Non-static methods are always called on an object created from the class the method is in. If no object is explicitly given, then the method is being called from within the class (or from a subclass) and the object is the same as that which the calling method was executing on and can be referenced by the keyword 'this'. Calling on a object created by a different class, you must explicitly give a reference to the object and its type must be cast at least to the type of the class where the method resides. To illustrate, from an Actor subclass
int h = getWorld().getHeight();
works because the method is in the World class and the object returned is a World type object. Now, let us say you had a getCounter method for your MyWorld objects (MyWorld extends World):
Counter counter = getWorld().getCounter();
will not work because there is no method with that name in the World class or any of its super-classes (which, btw, is limited to just the java.lang.Object class).
Counter counter = ((MyWorld)getWorld()).getCounter();
would work as the type of the World object returned is cast to where the method is defined. So, basically a method is called using 'objectReference.methodName()' where the type of the reference is adequately specified so that the method can be found.
You need to login to post a reply.