Methods With Parameters
by
, January 29th, 2012 at 04:50 PM (1105 Views)
Discussed in my last post was how we implement multiple classes and execute methods from within these classes via the main class. We can actually send variables from the main class into a method of the secondary class and then use those variables as desired. We do this through the use of parameters. Let me show you what I mean. Here's class2 and what it does.
You'll notice that we have included String name as our parameters this time round. That's because, we want to get the string 'name' from our main class and output its value. Seems simple enough right? All we have to do now is tell our class1 to send this variable through. Here's class1, containing our main method.
You'll notice that we've created a new class2 object named class2Object. This allows us to use class2 and execute code from within. Next, we created a new string variable called name. This is the variable we want to send through to the second class. We've assigned it a value of 'Tony'. We can send this variable through to the second class by using our class2 object, a dot separator, the method from within class2 that we want to output, and the parameter of 'name' (the variable we're sending).
So long as the variable you use in class2Object.class2Method(name);, which would be 'name', matches the variable used in public void class2Method(String name){, you should be right to go ahead and use this variable from within class2.