Lets take a closer looks at methods in Java. As we have seen Class consist of state and behaviour. Methods are defined in Java Classes so alter the behaviour of objects.
Let’s consider a Java code to understand better about the Methods.
package info.FiveBalloons.Examples; public class Car { private String carModel = "Mitsibushi"; private String yearMade = "2012"; private int speed; public void changeSpeed(int newSpeed) { this.speed = newSpeed; System.out.println("New Speed of Car is " + newSpeed); } public void applyBrake() { System.out.println("Brakes Applied"); } public static void main(String args[]) { Car car1 = new Car(); System.out.println("Car Model is " + car1.carModel); System.out.println("Year Made is " + car1.yearMade); car1.changeSpeed(60); car1.applyBrake(); } }
In the above code, Class
Car consists of three methods changeSpeed(int newSpeed)
, applyBrake()
and main(String args[]). Methods in Java consists of following things
Access Modifier : This can be public
, private
or protected
, We will learn more about access modifiers in subsequent tutorials.
Return Type: Method can return any primitive dataType, array of Class object. In the above code void
denotes that method will not return anything.
Method Name: Every method has a unique name, A single class can consist of multiple methods with same name, but with different parameters. This is called Method Overloading. More about this ahead.
Method parameters: Method can take parameters as input and there can be any number of parameter that can be passed to a method. For example methodName(String par1, int par2, int[] par3)
Method Overloading
A single class can consist of more methods with same name, but their parameters should be different. By doing this we can achieve method overloading. For example consider the above code which has a method named changeSpeed(int newSpeed)
, we can add a new method to the same class which has same name but accepts different set of parameters.
public class Car { private String carModel = "Mitsibushi"; private String yearMade = "2012"; private int speed; public void changeSpeed(int newSpeed) { this.speed = newSpeed; System.out.println("New Speed of Car is " + newSpeed); } public void changeSpeed(int originalSpeed, int addSpeed) { this.speed = originalSpeed + addSpeed; System.out.println("New Speed of Car is " + this.speed); } public void applyBrake() { System.out.println("Brakes Applied"); } public static void main(String args[]) { Car car1 = new Car(); System.out.println("Car Model is " + car1.carModel); System.out.println("Year Made is " + car1.yearMade); car1.changeSpeed(60); car1.applyBrake(); } }
In the above code we have added a new changeSpeed method which accepts two int parameters. Note that method overloading cannot be achieved just by changing the return type of the method.