Answers

Question and Answer:

  Home  Java Software Engineer

⟩ Explain me what is method overloading and method overriding?

☛ Method Overloading:

In Method Overloading, Methods of the same class shares the same name but each method must have different number of parameters or parameters having different types and order.

Method Overloading is to “add” or “extend” more to method’s behavior.

It is a compile time polymorphism.

The methods must have different signature.

It may or may not need inheritance in Method Overloading.

Let’s take a look at the example below to understand it better.

class Adder {

Static int add(int a, int b)

{

return a+b;

}

Static double add( double a, double b)

{

return a+b;

}

public static void main(String args[])

{

System.out.println(Adder.add(11,11));

System.out.println(Adder.add(12.3,12.6));

}}

☛ Method Overriding:

In Method Overriding, sub class have the same method with same name and exactly the same number and type of parameters and same return type as a super class.

Method Overriding is to “Change” existing behavior of method.

It is a run time polymorphism.

The methods must have same signature.

It always requires inheritance in Method Overriding.

Let’s take a look at the example below to understand it better.

class Car {

void run(){

System.out.println(“car is running”);

}

Class Audi extends Car{

void run()

{

System.out.prinltn(“Audi is running safely with 100km”);

}

public static void main( String args[])

{

Car b=new Audi();

b.run();

}

}

 168 views

More Questions for you: