Blog

Method Overloading in Java

  • (4.0)
  • | 683 Ratings

When one class have the same method names but they differ by parameter declaration then methods are called overloaded and this mechanism is called method overloading. When any overloaded method is called, JVM determines which method to call by checking type and number of the parameters. Let us understand this by below example.

class overloadDemo {
void print() {
System.out.println("0 Parameter");
}
// Overload print for one integer parameter.
void print(int i) {
System.out.println("i:" + i);
}
 
void print(int i, int j) {
System.out.println("i and j : " + i + " " + j);
}
// Overload print for a double parameter
double print(double e) {
System.out.println("e: " + e);
return e*e;
}
}
 
public class demo {
public static void main(String args[]) {
overloadDemo o = new overloadDemo();
double r;
// call all versions of print()
o.print();
o.print(5);
o.print(15, 10);
r = o.print(0.80);
System.out.println("r : " + r);
}
}

Output:

0 Parameter
i:5
i and j : 15 10
e: 0.8
r: 0.6400000000000001

Here we can see method print is overloaded with 4 different versions. The first version is not returning anything and is not taking any parameters as well. The second version is accepting an integer parameter without returning any value. The third version is accepting 2 integer parameters without retuning anything. The fourth version is accepting double type parameter and is returning double value to the caller. Whenever the overloaded method is called, Java will look for the best match and call that method which has the same parameter type and return type.

constructor overloading in java with example

Along with methods, Java also allows overloading of constructors. When any object is created, we can initialize it with different values. But when we don’t want to initialize it with any values or when we want to initialize only with one value, at that time we can use constructors overloading. Let us understand it in detail by below example:

class boxDemo {
double width;
double height;
double depth;
 
boxDemo(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
boxDemo() {
width = -1; 
height = -1; 
depth = -1; }
 
boxDemo(double len) {
width = height = depth = len;
}
 
double volume() {
return width * height * depth;
}
}
public class overloadDemo {
public static void main(String args[]) {
 
boxDemo ob1 = new boxDemo(5, 15, 25);
boxDemo ob2 = new boxDemo();
boxDemo ob3 = new boxDemo(5);
double v;
 
v = ob1.volume();
System.out.println("volume of ob1 is " + v);
 
v = ob2.volume();
System.out.println("volume of ob2 is " + v);
 
v = ob3.volume();
System.out.println("volume of ob3 is " + v);
}
}

Output:

volume of ob1 is 1875.0
volume of ob2 is -1.0
volume of ob3 is 125.0

Respective constructor will be called based upon the parameters passed to it.

Recursion in Java

When a method calls itself then it is called a recursive method and this mechanism is called recursion. The best example of recursion is factorial calculation of any number.

class factDemo {
// this is a recursive method
int fact(int n) {
int r;
if(n==1) return 1;
r = fact(n-1) * n;
return r;
}
}
public class recursionDemo {
public static void main(String args[]) {
factDemo f = new factDemo();
System.out.println("Factorial of 2 is " + f.fact(2));
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
}
}

Output:

Factorial of 2 is 2
Factorial of 3 is 6
Factorial of 4 is 24

Its main advantage is to develop the code of few algorithms in a simpler and clearer way. 

Inheritance injava

Java provides the mechanism called inheritance where one class can acquire the properties and behavior of another class. We can group this concept into 2 below groups:

  • superclass(parent): class that is inherited
  • subclass(child): class inheriting other class

Subclass inherits all the variable and methods of superclass and adds its own unique properties. In Java, we use the keyword extends to inherit the class.

Let us understand through below simple example.

class X {
int i;
void printi() {
System.out.println("i: " + i );
}
}
// Create a subclass by extending class A.
class Y extends X {
int j;
void printj() {
System.out.println("j: " + j);
}
void sum() {
System.out.println("i+j" + (i+j));
}
}
 
public class Main
{
    public static void main(String[] args) {
    X superOb = new X();
    Y subOb = new Y();
 
    superOb.i = 5;
   
    System.out.println("Super Class");
    superOb.printi();
    
    subOb.i = 10;
    subOb.j = 8;
  
    System.out.println("Sub Class");
    subOb.printi();
    subOb.printj();
    subOb.sum();
    }
}

Output:

Super Class                                                                                                                                      
i: 5                                                                                                                                             
Sub Class                                                                                                                                        
i: 10                                                                                                                                            
j: 8                                                                                                                                             
i+j18   

Here subclass Y can access all members of super class X. That is why object of subclass Y subOb can access variable i and method printi().

Types of Inheritance

Java supports various types of inheritances.

  • Single Inheritance

In this type of inheritance, only one class extends another class.

img

Here, class X is extended by class Y. Class Y becomes subclass and class X becomes superclass.

  • Multiple Inheritance

In multiple inheritance, one class extends more than one class. Java doesn’t support multiple inheritance.

  • Multilevel Inheritance

In multilevel inheritance, one class is inherited by other class. And some other class can also inherit the child class. 

Class Y is subclass of class X and class Z is subclass of class Y.

  • Hierarchical Inheritance

In hierarchical inheritance, many classes can inherit the same class.

Here, class X, Y and Z are subclasses of same class W.

  • Hybrid Inheritance

Hybrid inheritance is a combination of single and multiple inheritance. As Java doesn’t support multiple inheritance, hybrid inheritance is also not supported by Java.

Constructors behavior for inherited classes

When any class hierarchy is created, constructors are called from superclass to subclass. Below example will illustrate the same.

class X {
X() {
System.out.println("Inside X's constructor.");
}
}
class Y extends X {
Y() {
System.out.println("Inside Y's constructor.");
}
}
 
class Z extends Y {
Z() {
System.out.println("Inside Z's constructor.");
}
}
public class Main
{
    public static void main(String[] args) {
        Z obj = new Z();
    }
}

Output:

Inside X's constructor.                                                                                                                        
Inside Y's constructor.                                                                                                                        
Inside Z's constructor.

Method Overriding in Java

If subclass has the same method name and signature like superclass, then subclass overrides the method in superclass. So, when the method is called from subclass, it will always execute the code defined in the subclass method. Superclass method code will be hidden. Let us understand it more through below example:

class X {
void printDetails() {
System.out.println("Inside Superclass Method.");
}
}
 
class Y extends X {
void printDetails(){
System.out.println("Inside Subclass Method");
}
}
 
 
public class Main
{
    public static void main(String[] args) {
        Y obj = new Y();
        obj.printDetails();
    }
}

Output:

Inside Subclass Method

When a subclass object is invoking the overridden method, it will always call subclass version of method. Here in this example, object of Y class will call printDetails() method defined in subclass Y only.

In Java, we have a keyword super to access superclass version of method. Let just modify above example a little and see the output.

class X {
void printDetails() {
System.out.println("Inside Superclass Method.");
}
}
 
class Y extends X {
void printDetails(){
super.printDetails();
System.out.println("Inside Subclass Method");
}
}
 
 
public class Main
{
    public static void main(String[] args) {
        Y obj = new Y();
        obj.printDetails();
    }
}

Output:

Inside Superclass Method.
Inside Subclass Method

When names and types are same for methods then it is called method overriding. But if we have other differentiator for 2 methods, then that becomes method overloading which we have already learnt in previous section.

Subscribe For Free Demo

Free Demo for Corporate & Online Trainings.

Ravindra Savaram
About The Author

Ravindra Savaram is a Content Lead at Mindmajix.com. His passion lies in writing articles on the most popular IT platforms including Machine learning, DevOps, Data Science, Artificial Intelligence, RPA, Deep Learning, and so on. You can stay up to date on all these technologies by following him on LinkedIn and Twitter.


DMCA.com Protection Status

Close
Close