In this tutorial I will show you how to call methods. For the purpose of this tutorial, the objects that I will be using are assumed to have already been created. The methods that I will be using are coming from a class called cauldron.
cauldron.add(tomato, chicken, basil);
This is what out method call looks like. The cauldron object has a method called add() it takes three arguments in its formal parameter-list. The formal parameter-list is the space between the ( and the ) brackets. What we use this for is to pass information to the method. Lets take a look at our method header for add():
add (vegetable veg, meat meat, herb herb)
All the characters between ( and ) make up the parameter list and they are separated by commas. Each segment that is split up by commas are known as arguments. The arguments can only take objects of certain types. For example vegetable veg can take arguments with different name the veg but it can only take variables of the type vegetable. So when you put arguments in you formal parameter list make sure that you have the types correct.
So now that I have covered the terms let us create some basic code.
vegetable tomato ;
meat chicken;
herb basil;
cauldron pot = cauldron. add(tomato, chicken, basil);
What we did with:
vegetable tomato;
meat chicken;
herb basil;
We assign these variables to a specific type so that we can pass them as arguments in our formal parameter list to be used by the add method.
Then we called our method:
cauldron pot = cauldron. add(tomato, chicken, basil);
We assigned this method to a variable called pot of the cauldron type. Then we call our method, add(tomato, chicken, basil); , from the cauldron object. The variables we created are passed into the method and used.
The code inside the method is never run until it is called. This code will not work if variables in the parameter list are of the wrong type.
Created by John Longanecker for CSE115