Method Overloading in Java

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

If you would like to become a Core Java Certified professional, then visit Mindmajix - A Global online training platform: "Core java Certification Training Course".This course will help you to achieve excellence in this domain.

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 returning anything. The fourth version is accepting a double type parameter and is returning a double value to the caller. Whenever the overloaded method is called, Java will look for the best match and call that method that 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 the 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

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

[ Related Article:- Java Tutorial ]

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 a 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. 

[ Related blog:- Java Interview Questions ]

Inheritance in java

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): a class that is inherited
  • subclass(child): class inheriting another class

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

Let us understand through the 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 superclass X. That is why the object of subclass Y subOb can access variable i and method printi().

 MindMajix YouTube Channel

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 inheritances. As Java doesn’t support multiple inheritances, 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

[ Related Article:- Control Statements in Java ]

Method Overriding in Java

If the subclass has the same method name and signature as the superclass, then the subclass overrides the method in the superclass. So, when the method is called from the 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(){
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.

Job Support Program

Online Work Support for your on-job roles.

jobservice

Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:

  • Pay Per Hour
  • Pay Per Week
  • Monthly
Learn MoreGet Job Support
Course Schedule
NameDates
Core Java TrainingNov 23 to Dec 08View Details
Core Java TrainingNov 26 to Dec 11View Details
Core Java TrainingNov 30 to Dec 15View Details
Core Java TrainingDec 03 to Dec 18View Details
Last updated: 08 Oct 2024
About Author

I am Ruchitha, working as a content writer for MindMajix technologies. My writings focus on the latest technical software, tutorials, and innovations. I am also into research about AI and Neuromarketing. I am a media post-graduate from BCU – Birmingham, UK. Before, my writings focused on business articles on digital marketing and social media. You can connect with me on LinkedIn.

read less
  1. Share:
Java Articles