Sitemap
Shashane Ranasinghe

Shashane Ranasinghe

Methods in Java

6 min readFeb 19, 2022

Chapter 4

Press enter or click to view image in full size

A class consists of variables and methods. Objects of a class can have different values for the variables. The objects of the classes have the same methods, but they could have different behaviour since the instance variables can affect the behaviour of the methods.

Example:

The Dog class can have a bark method and an instance variable age, We could say that the tone of the bark of an older dog could be different from an older dog. we can demonstrate this like:

public void bark(){
if (age > 5) {
System.out.println("Wooof! Wooof!");
} else if (age > 3) {
System.out.println("Ruff! Ruff!");
} else {
System.out.println("Yip! Yip!");
}
}

We could have a bark function like this. Even though the function is the same for all the objects the behaviour could be different depending on the age of the dog.

Parameters in a method

A method can have parameters which can influence the behaviour of the method. We can change the bark method to accept a parameter that tells how many times to bark.

public void bark(int count){
for (int i = 0 ; i < count; i++){
System.out.println("Woof! Woof!");
}

in this method the bark method accepts a parameter of type int. And the loop will run based on the parameter. We can pass the arguments (when we pass the value to the method we call it an argument) to the method.

dog.bark(5);

we can pass the argument as shown above, the argument should be of the type that is required by the method. if the method requires a parameter you must pass a value to the method. We can pass variables to a method as long as it is the same type that is required by the method

We could also pass multiple parameters to a function.

public void getTotal(int x, int y){
int total = x + y;
System.out.println("Total is "+ total);
}
Calculate cal = new Calculate();
cal.getTotal(10,5);

similar to passing a single argument now we have two parameters within the parenthesis of the method. We can pass these arguments as shown in the last line. As earlier the values that we pass to the method should correspond to the types of the parameters. Since the method requires 2 int values, we have to pass 2 int values and the method will receive the values in the order we pass them.
In this example the value for x will be 10 and the value for y will be 5.

When we pass a variable to a method. there will be no connection between the value passed and the variable. even though the value passed is changed inside of the function is changed it wouldn't affect the variable

Example

public void testMethod(int x){
x = 0;
}

int z = 10;
testmethod(z);

In the above method we pass a variable z to the test method. Even though the value we passed is set to zero inside the test method, it will not change the value of z, The value of z will still be 10.

Return from a method

While you can pass values to the method, you can get values from the method too. We can give a return type to the method when declaring a method.

public int getTotal(int x, int y){
int total = x + y;
return total;
}

The above method has 2 parameters x and y and it calculates the total. As you can see there is the datatype of the return value before the method name. it says that the method will return a value of type int. At the end of the function we can see that it returns the total. If you declare a method with a return type you must return a value of that type. We can get the value that has been returned by the function.

Calculate cal = new Calculate();
int total = cal.getTotal(10,5);

the variable total will store the value that is returned by the getTotal method.

Get Shashane Ranasinghe’s stories in your inbox

Join Medium for free to get updates from this writer.

Getters and Setters (Accessors and Mutators)

We have instance variables in a class. The purpose of a getter is to get the value of a instance variable of a class. While the purpose of a setter is to set the value for the instance variable.

Example: consider a class with a variable age. We can have a getter called getAge() to get the age and a setter called setAge() to set the age.

public class Dog {
int age;

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

}

The class would look like this, The getAge method will return us the age of the dog, while the setAge method will take a parameter and set that value as the age.

Consider the following class

public class Dog {
String name;
int age;
String breed;

public void eat(){
//Implementation
}
public void sleep(){
//Implementation
}
public void bark(int count){
//Implementation
}
}

If we have a class like this anyone can access the class variables with ease as shown as below

Dog dog = new Dog();
dog.age = -1;

This is not a good thing, and it is a violation of Object Oriented Programming. because the instance variables are exposed to everyone and using the dot operator anyone can change the values to anything that they want. To avoid this we use getters and setters, and we can put checks as shown below

public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}

and then we need to restrict the access of the data. to do this we can change the access modifiers of the variables. There are 4 types of access modifiers

  1. Public — Accessible to everyone
  2. Private — Only accessible from within the class
  3. Protected — Accessible within the package, and outside the package through a child class
  4. Default — accessible within the package
    If no access modifier is provided Java uses the default access modifier

So by using the Private access modifier we can prevent everyone from having access to the variables.

This is called encapsulation, It means to wrap the data into a single unit and protect the data by restricting the access for this data from outside this unit.

As a rule of thumb of encapsulation we mark the variables as private and the getters as public.

By using encapsulation we can force the code outside the unit to go through the setters and we can have validate and decide of we allow them to do the changes. Also by using setters if we need to add a new validation we can add the validation without disrupting the others code.

An encapsulated class would look like this

public class Dog {
private int age;

public int getAge() {
return age;
}

public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
public void bark(){
if (age > 5) {
System.out.println("Wooof! Wooof!");
} else if (age > 3) {
System.out.println("Ruff! Ruff!");
} else {
System.out.println("Yip! Yip!");
}
}
}

As you can see the instance variables are private and the getters and setters are public.

We now know that the getter methods gives us the values of the instance variables. but what would happen if we call the getter method before setting the value to the variable?
It would provide us with the default value of the variable. all instance variables have a default value depending on their datatype.
Examples of default values

intergers : 0
floating point numbers: 0.0
boolean : false
references : null

You can get to know about Java by checking out my list on introduction to Java, by clicking here

References

  1. Kathy Sierra and Bert Bates. 2005. Head First Java, 2nd Edition. O’Reilly & Associates, Inc., USA.

--

--