Many Methods & Instances
by
, January 29th, 2012 at 04:52 PM (1321 Views)
This post goes over how we can use multiple methods in different classes. It's a very inefficient program we've written, but it's designed to show you exactly what each method does and how they relate to each other. Here's Class2, the guts of the application. I've included comments to show you what everything does.
public class Class2 { //New string private String friendName; /* This method is responsible for collecting the name * variable we sent from the main method. We assign * the variable friendName to the name collected in * the main method. */ public void setName(String name){ friendName=name; } //New method with a return type of String public String getName(){ /* Basically just inserts the friendName variable * into the getName method.*/ return friendName; } //New method for finally outputting our name variable public void outputName(){ //Outputs the variable getName System.out.printf("Your friend's name is %s", getName()); } }
The application basically outputs someone's name which we collect from Class1. Basically, we start by creating a friendName variable that we can use in Class2. It's going to be responsible for carrying our friend's name throughout the series of methods we've created here. Our first method, setName assigns the variable name (sent from Class1) to our friendName variable.
The next method, which is pretty useless, simply assigns the variable of friendName to the method of getName. This way we can use it in our last method, outputName by simply calling the getName method (which is storing our friendName variable). Let's take a look at Class1.
class Class1{ public static void main(String args[]){ //New object for Class2 Class2 class2Object = new Class2(); //New string String name = "Tony"; //Send the variable 'name' to setName method in Class2 class2Object.setName(name); //Run the outputName method in Class2 class2Object.outputName(); } }
All we're doing here is creating a new object for Class2, followed by creating our name string, followed by sending this variable via our object through to the setName method in Class2.
I know it seems stupid using four different methods to output a simple variable, but it shows us how we can use multiple methods with multiple purposes for each to get the job done. Obviously this sort of setup would be better used had we had many more operations we wished to carry out.