Method Overloading in Different Classes in Java
Last Updated :
15 Sep, 2022
Methods of a class said to be overloaded if
- Both declared in the same class, or
- Both inherited by a class, or
- One declared and one inherited
And have the same name but a different signature. Refer to this article, Different ways of Method Overloading in Java, for a basic understanding of method overloading. The below programs demonstrate the same.
Case 1: If both methods declared in the same class
Java
class Demo {
public void display()
{
System.out.println( "in Demo display " );
}
public void display( int n)
{
System.out.println( "in Demo display n : " + n);
}
}
class GFG {
public static void main(String[] args)
{
Demo d = new Demo();
d.display();
d.display( 10 );
}
}
|
Output:
in Demo display
in Demo display n : 10
Explanation:
In the above example, the Demo class defines two methods display() and display(int n). both are having the same name yet different signatures. Thus this two methods of Demo class are said to be overloaded.
Case 2: If both methods are inherited by a class
Java
class Base {
public void display()
{
System.out.println( "in Base display " );
}
public void display( int n)
{
System.out.println( "in Base display n : " + n);
}
}
class Derived extends Base {
public Derived()
{
System.out.println( "\nDerived class Constructor.." );
}
}
class GFG {
public static void main(String[] args)
{
Derived d = new Derived();
d.display();
d.display( 10 );
}
}
|
Output:
Derived class Constructor..
in Base display
in Base display n : 10
Explanation:
In the above example Base class define two methods display() and display(int n). The derived class extends the Base class Thus it inherits the methods of the Base class (display() and display(int n)). Although this two methods are not defined in the Derived class(inherited from Base), they are having the same name and different signatures. Thus they are said to be overloaded.
Case 3: If one method is declared and one is inherited
Java
class Base {
public void display()
{
System.out.println( "in Base display " );
}
}
class Derived extends Base {
public int display( int n)
{
System.out.print( "\nin Derived display n : " );
return n;
}
}
class GFG {
public static void main(String[] args)
{
Derived d = new Derived();
d.display();
int n = d.display( 10 );
System.out.println(n);
}
}
|
Output:
in Base display
in Derived display n : 10
Explanation:
In the above example, the Base class defines the display() method. Derived class defines display(int n) method and inherits display() from Base class. Both the methods (in the Derived class- one defined and one inherited) have the same name but different signatures. Thus they are said to be overloaded.
Note: In Example 3 note the signature and return type of both methods. Both are different thus this is not overriding but overloading.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...