Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

Java

Learn step by step



Methods in Java

Method describe behavior of an object. A method is a collection of statements that are group together to perform an operation.

A Method has the following general syntax 2:

return-type methodName(parameter-list)
{
//body of method
}

EXAMPLE :

public String getName(String st)
{
String name="StudyTutOn";
name=name+st;
return name;
}
Method

Fig1.

Modifier : Modifier are access type of method. We will discuss it in detail later.

Return Type : A method may return value. Data type of value return by a method is declare in method heading.

Method name : Actual name of the method

Parameter : Value passed to a method.

Method body : collection of statement that defines what method does.

Parameter Vs. Argument

While talking about method, it is important to know the difference between two terms parameter and argument.

Parameter is variable defined by a method that receives value when the method is called. Parameter are always local to the method they dont have scope outside the method. While argument is a value that is passed to a method when it is called.

Method

Fig2.

There are two ways to pass an argument to a method

  • call-by-value : In this approach copy of an argument value is pass to a method. Changes made to the argument value inside the method will have no effect on the arguments.
  • call-by-reference : In this reference of an argument is pass to a method. Any changes made inside the method will affect the agrument value.

NOTE : In Java, when you pass a primitive type to a method it is passed by value whereas when you pass an object of any type to a method it is passed as reference.

Example of Call-by-value.


public class Test
{
public void callByValue(int x)
{
x=100;
}
public static void main(String[] args)
{
int x=50;
Test t = new Test();
t.callByValue(x); <font color="green">//function call</font>
System.out.println(x);
}

}

Output

50

Example of Call-by-reference.


public class Test
{
int x=10;
int y=20;
public void callByReference(Test t)
{
t.x=100;
t.y=50;
}
public static void main(String[] args)
{

Test ts = new Test();
System.out.println("Before "+ts.x+" "+ts.y);
ts.callByReference(ts);
System.out.println("After "+ts.x+" "+ts.y);
}

}

Output

Before 10 20
After 100 50


Method Overloading

A typical program involves a great deal of names that represent variables and methods of various kinds. The compiler does not allow two variables to have the same name in the same method. Although two methods should have unique names in the same program, a class can have different methods with the same name if you follow some rules. The ability to have various methods with the same name in the same program is referred to as method overloading. To perform overloading, the methods must have different numbers or different type(s) of arguments.

The moment of inertia is the ability of a beam to resist bending. It is calculated with regard to the cross section of the beam. Because it depends on the type of section of the beam, its calculation also depends on the type of section of the beam. In this exercise, we will review different formulas used to calculate the moment of inertia. Since this exercise is for demonstration purposes, you do not need to be a Science Engineering major to understand it.

How to achieve method overloading in java

Method overloading in Java occurs when two or more methods shares same name and fulfill at least one of the following condition.

  • 1) Have different number of arguments.
  • 2) Have same number of arguments but their types are different.
  • 3) Have both different numbers of arguments with a difference in their types.

Method overloading in same class.

Overloading occurs in a single class when two or more methods shares a same name with a ‘difference in number of arguments’ or ‘difference in argument type’ or both.


public class Test
{
int x=10;
int y=20;
public void callByReference(Test t)
{
t.x=100;
t.y=50;
}
public static void main(String[] args)
{

Test ts = new Test();
System.out.println("Before "+ts.x+" "+ts.y);
ts.callByReference(ts);
System.out.println("After "+ts.x+" "+ts.y);
}

}
Method overloading in subclass

It is also possible to overload methods in sub classes, as long as the methods shares same name and they are different in the number of parameters or type of parameters.


public class Fruit {
public void getFruit(int fruitId){
......
}
}

public class Apple extends Fruit {

public void getFruit(String name) {
......
}
public void getFruit(int fruitId, String name) {
......
}

}
How to not overload method

Methods having same name in one class or in child class could not perform method overloading if they are just different in: 1) Name of argument, and not in number of arguments or type of arguments. 2) Having different return type only.


/*
* Just a difference in name of parameters and not in their number or type
* is not method overloading, it will give an compilation error
*/
public void getEmpName(int empId) {
......
}

public void getEmpName(int employeeId) {
......
}

/*
* It is not method overloading with just difference in return type of
* methods of having same name, and not different in number of paramets or
* type of parameter.
*/
public void getFruit(String name){
....

}

public String getFruit(String name){
....

return "Apple";
}
How method overloading helps in Java

When it comes to, why to use method overloading and usage of method overloading. Two points comes out
1) Helps in maintain consistency in method naming, doing same task with just a difference of input parameter. 2) Helps in reduce overhead of remember name of different functions for same task, one can pass possible different type of parameters or number of parameters to a single overloaded function to get the result.


/*
* This is purely inconsistent and rubbish to have three different names of
* methods for doing same task, all are just returning Employee.
*/
public Employee getEmpById(int empId) {
......
}

public Employee getEmpByName(String empName) {
......
}

public Employee getEmpByDob(Date dob) {
......
}

/*
* Its better to overload methods with same functionality, this make the
* code consistent and reduce overhead of remember method names with
* different type and number of input parameter. This way user just need to
* pass available input parameter to the same method.
*/
public Employee getEmp(int empId) {
......
}
public Employee getEmp(String empName) {
......
}
public Employee getEmp(Date dob) {
......
}


Different ways to overload the method

There are two ways to overload the method in java

  • 1.By changing number of arguments
  • 2.By changing the data type

In this example, we have created two overloaded methods, first sum method performs addition of two numbers and second sum method performs addition of three numbers.


class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}

public static void main(String args[]){
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);

}
}

Output

30
40

In this example, we have created two overloaded methods that differs in data type. The first sum method receives two integer arguments and second sum method receives two double arguments.


class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}

public static void main(String args[]){
Calculation obj=new Calculation();
obj.sum(10.5,10.5);
obj.sum(20,20);

}
}

Output

21.0
40


Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding.

In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as Method Overriding.


Advantage of Java Method Overriding

  • Method Overriding is used to provide specific implementation of a method that is already provided by its super class.
  • Method Overriding is used for Runtime Polymorphism


Rules for Method Overriding

  • method must have same name as in the parent class.
  • method must have same parameter as in the parent class.
  • must be IS-A relationship (inheritance).


Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use method overriding.


class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{

public static void main(String args[]){
Bike obj = new Bike();
obj.run();
}
}

Output

Vehicle is running

Problem is that I have to provide a specific implementation of run() method in subclass that is why we use method overriding.

In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding.


class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){
Bike obj = new Bike();
obj.run();
}

Output

Bike is running safely

What is the difference between method Overloading and Method Overriding?

There are three basic differences between the method overloading and method overriding. They are as follows:


Method Overloading Method Overriding
1) Method overloading is used to increase the readability of the program.Method overriding is used to provide the specific implementation of the method that is already provided by its super class.
2) method overloading is performed within a class.Method overriding occurs in two classes that have IS-A relationship.
3) In case of method overloading parameter must be different.In case of method overriding parameter must be same.


Related Videos