Using methods demo apps

Here, we will quickly build two apps to explore methods a bit further. First, we will explore the fundamentals with the Real World Methods app, and then we will glimpse a new topic, method overloading, in action with the Exploring Method Overloading app.

As we normally do, you can open the ready-typed code files in the usual way. The following two examples on methods can be found in the PACKT download in the chapter 8 folder and the Real World Methods and Exploring Method Overloading sub-folders.

Real world methods

First, let's make ourselves some simple working methods, complete with return type parameters and fully functioning bodies.

To get started, create a new Android project called Real World Methods, use an Empty Activity, and leave all the other settings at their default settings. Switch to the MainActivity.java file by left-clicking the MainActivity.java tab above the editor and we can start coding.

First, add these three methods to MainActivity. Add them just after the closing curly brace } of the onCreate method:

String  joinThese(String a, String b, String c){
   return a + b + c;
}

float getAreaCircle(float radius){
   return 3.141f * radius * radius;
}

void changeA(int a){
   a++;
}

The first method we added is called joinThese. It will return a String and needs three String variables passed into it. In the method body, there is only one line of code. The code return a + b + c will concatenate the three strings that are passed into it and return the joined strings as the result.

The next method, getAreaCircle, takes a float variable as an argument and then returns a float variable too. The body of the method simply uses the formula for the area of a circle, incorporating the passed-in radius, and then returns the answer to the calling code. The odd-looking f on the end of 3.141 is used to let the compiler know that the number is of the float type. Any floating point number is assumed to be of the double type unless it has the trailing f.

The third and final method is the simplest of all the methods. Notice that it doesn't return anything; it has a void return type. We have included this method to make an important point clear: we want to remember about methods. But let's see it in action before we talk about it.

Now, in onCreate, after the call to setContentView, add the following code, which calls our methods and outputs some text to the logcat:

String joinedString = joinThese("Methods ", "are ", "cool ");
Log.e("joinedString = ","" + joinedString);

float area  = getAreaCircle(5f);
Log.e("area = ","" + area);

int a = 0;
changeA(a);
Log.e("a = ","" + a);

Run the app and see the output in the logcat window, which is provided here for your convenience:

joinedString =﹕ Methods are cool
area =﹕78.525
a =﹕ 0

In the logcat output, the first thing we can see is the value of the joinedString string. As expected, it is the concatenation of the three words we passed into the joinThese method.

Next, we can see that the getAreaCircle has indeed been calculated and returned the area of a circle based on the length of the radius passed in.

Discovering variable scope

The final line of output is the most interesting: a=: 0. In the onCreate method, we declared and initialized int a to zero, and then we called changeA. In the body of changeA, we incremented a with the code a++. Yet, back in onCreate, we can see that when we use Log to print the value of a to the logcat window, it is still 0.

So, when we passed in a to the changeA method, we were actually passing the value stored in a, not the actual variable a. This is referred to as passing by value in Java.

Tip

When we declare a variable in a method, it can only be seen in that method. When we declare a variable in another method, even if it has the exact same name, it is NOT the same variable. A variable only has scope within the method it was declared.

With all primitive variables, this is how passing them to methods works. With reference variables, it works slightly different, and we will see how in the next chapter.

Note

I have talked about this scope concept with a number of people new to Java. To some it seems blindingly obvious, even natural. To others, however, it is a cause of constant confusion. Should you fall into the latter category, don't worry, because we will talk a bit more about this later in this chapter, and, in future chapters, we will explore scope in greater depth and make sure that it is no longer an issue.

Let's look at another practical example of methods and learn something new at the same time.

Exploring method overloading

As we are learning, methods are quite deep as a topic. But, hopefully, taking them a step at a time, we will see that they are not daunting in any way. We will also be returning to methods in the next chapter. For now, let's create a new project to explore method overloading.

Create a new Empty Activity project called Exploring Method Overloading, and then we will get on with writing three methods, but with a slight twist.

As we will now see, we can create more than one method with the same name, provided that the parameters are different. The code in this project is very simple. It is how it works that might appear slightly curious until we analyze it subsequently.

In the first method, we will simply call it printStuff and pass in an int variable via a parameter to be printed. Insert this method after the closing } of onCreate, but before the closing } of MainActivity. Remember to import the Log class in the usual way:

void printStuff(int myInt){
   Log.i("info", "This is the int only version");
   Log.i("info", "myInt = "+ myInt);
}

In this second method, we will also call it printStuff, but pass in a String variable to be printed. Insert this method after the closing } of onCreate, but before the closing } of MainActivity:

void printStuff(String myString){
   Log.i("info", "This is the String only version");
   Log.i("info", "myString = "+ myString);
}

In this third method, we will also call it printStuff, but pass in a String variable and an int to be printed. Insert this method after the closing } of onCreate, but before the closing } of MainActivity:

void printStuff(int myInt, String myString){
   Log.i("info", "This is the combined int and String version");
   Log.i("info", "myInt = "+ myInt);
   Log.i("info", "myString = "+ myString);
}

Now, insert this code just before the closing } of the onCreate method to call the methods and print some values to the logcat:

// Declare and initialize a String and an int
int anInt = 10;
String aString = "I am a string";
        
// Now call the different versions of printStuff
// The name stays the same, only the parameters vary
printStuff(anInt);
printStuff(aString);
printStuff(anInt, aString);

Now, we can run the run the app on the emulator or a real device.

Here is the console output:

info﹕ This is the int only version
info﹕ myInt = 10
info﹕ This is the String only version
info﹕ myString = I am a string
info﹕ This is the combined int and String version
info﹕ myInt = 10
info﹕ myString = I am a string

As you can see, Java has treated three methods with the same name as different methods. This, as we have just shown, can be useful. It is called method overloading.

Note

Method overloading and overriding confusion

Overloading is when we have more than one method with the same name but different parameters.

Overriding is when we replace a method with the same name and the same parameter list.

We know enough about overloading and overriding to complete this book, but if you are brave and your mind is wandering, yes, you can override an overloaded method, but that is something for another time.

This is how it all works. In each of the steps where we wrote code, we created a method called printStuff. But each printStuff method has different parameters, so each is actually a different method that can be called individually:

void printStuff(int myInt){
   ...
}

void printStuff(String myString){
   ...
}

void printStuff(int myInt, String myString){
   ...
}

The body of each of the methods is trivial and just prints out the passed-in parameters and confirms which version of the method is being called.

The next important part of our code is when we make it plain what we mean to call by using the specific arguments that match the parameters in the signature. In the final step, we call each in turn by using the matching parameters so that Java knows the exact method required:

printStuff(anInt);
printStuff(aString);
printStuff(anInt, aString);

We now know all we need to about methods, so let's take a quick second look at the relationship between methods and variables and then get our heads around this scope phenomenon a bit more.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.85.142