Question

I am trying to understand a sample code in Webots (robot simulation program).

I have faced this code :

Servo rightShoulderPitch = getServo("RShoulderPitch");
rightShoulderPitch.setPosition(1.5);

I do not understand what is meat by the first line. It look like that "rightShoulderPitch" is an object of Servo class but it is not created as usual and how 'getServo' (i think it is a method) comes here .

This class's header is, if it helps:

public class FieldPlayer extends Robot {

Also it has description by the company in the reference manual, but I could not understand what they mean. It can be found here search for getservo.

--- RShoulderPitch: is the name of the shoulder of the robot

I will appriceite help very much.

Thanks

Was it helpful?

Solution

To complement Jon's excellent answer, I'll try to explain you in much more general terms.

When you want a sandwich, you have two solutions:

  • prepare the sandwich yourself. This would be the equivalent of the code Sandwich s = new Sandwich()
  • go to a snack bar and ask them a sandwich. This would be the equivalent of the code Sandwich s = snackBar.getSandwich("Ham & Cheese").

In the latter case, it's the snackBar object's getSandwich() method which will use the name of the sandwich you want ("Ham & Cheese") to prepare a sandwich and return it for you. This method will thus probably, internally, call new Sandwich(). But it could also delegate to another object and call, for example: cook.prepareSandwich("Ham & Cheese"). And in this case, it's the cook object which will call new Sandwich(). Or the snackBar object could also just get a sandwich that has been prepared in advance and stored in some cache: fridge.getSandwich("Ham & Cheese").

OTHER TIPS

This line:

Servo rightShoulderPitch = getServo("RShoulderPitch");

... calls the getServo method, passing in the string value "RShoulderPitch". The return value is used as the initial value of the rightShoulderPitch variable, which is of type Servo. (Note that rightShoulderPitch isn't an object - it's a variable. It has a value, which would either be null or a reference to an object.)

We can't tell what the return type of getServo is, but it's got to be something which is implicitly convertible to Servo - so either Servo itself, or some subclass.

getServo could:

  • Create a new object, and return a reference to it
  • Return a reference to an existing object (e.g. from a cache)
  • Return null
  • Throw an exception

If none of that helps, please clarify exactly what you don't understand. It sounds like you may be new to Java - in which case, learning "just Java" without the Webots API would probably be a good approach; only learn Webots when you're confident in the language itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top