Q8. 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 a different number of parameters or parameters having different
types and order.
Method Overloading is to “add” or “extend” more to the method’s behavior.
It is a compile-time polymorphism.
The methods must have a 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.
Java Certification Training Course
Instructor-led Sessions
Real-life Case Studies
Assignments
Lifetime Access
Explore Curriculum
1 class Adder {
2 Static int add(int a, int b)
{
3
return a+b;
4
}
5
Static double add( double a, double b)
6
{
7 return a+b;
8 }
9 public static void main(String args[])
10 {
11
System.out.println(Adder.add(11,11));
12
System.out.println(Adder.add(12.3,12.6));
13
}}
14
Method Overriding:
In Method Overriding, the subclass has the same method with the same name and
exactly the same number and type of parameters and same return type as a
superclass.
Method Overriding is to “Change” existing behavior of the method.
It is a run time polymorphism.
The methods must have the same signature.
It always requires inheritance in Method Overriding.
Let’s take a look at the example below to understand it better.
1
class Car {
2
void run(){
3
System.out.println(“car is running”);
4
}
5 Class Audi extends Car{
6 void run()
7 {
8 System.out.prinltn("Audi is running safely with 100km");
9 }
public static void main( String args[])
10
{
11
Car b=new Audi();
12
b.run();
13
}
14
}
15
Q9. Can you override a private or static method in Java?
You cannot override a private or static method in Java. If you create a similar method
with the same return type and same method arguments in child class then it will hide
the superclass method; this is known as method hiding. Similarly, you cannot
override a private method in subclass because it’s not accessible there. What you
can do is create another private method with the same name in the child class. Let’s
take a look at the example below to understand it better.