overloading vs overriding java code example
Example 1: overloading vs overriding
Method Overloading
Method overloading is providing two separate methods in a class
with the same name but different arguments, while the method return type
may or may not be different, which allows us to reuse the same method name.
1) Method Overloading occurs with in the same
class
2) Since it involves with only one class inheritance
is not involved.
3)In overloading return type need not be the same
4) Parameters must be different when we do
overloading
5) Static polymorphism can be acheived using
method overloading
6) In overloading one method can’t hide the
another
Method Overriding
Overriding means same method name and same parameter,
occur in different class that has inheritance relationship.
we use method overriding to implement specific functionality to the method.
1) Method Overriding occurs between
two classes superclass and subclass
2) Since method overriding occurs between superclass
and subclass inheritance is involved.
3) In overriding return type must be same.
4) Parameters must be same.
5) Dynamic polymorphism can be acheived using
method overriding.
6) In overriding subclass method hides that of the
superclass method
Example 2: overriding vs overloading
Method Overloading
Method overloading is providing two separate
methods in a class with the same name but
different arguments, while the method return type
may or may not be different,
which allows us to reuse the same method name.
1) Method Overloading occurs with in the same class
2) Since it involves with only one class inheritance
is not involved.
3)In overloading return type need not be the same
4) Parameters must be different when we do
overloading
5) Static polymorphism can be acheived using
method overloading
6) In overloading one method can’t hide the another
Method Overriding
Overriding means same method name and same parameter,
occur in different class that has inheritance relationship.
we use method overriding to implement
specific functionality to the method.
1) Method Overriding occurs between
two classes superclass and subclass
2) Since method overriding occurs between superclass
and subclass inheritance is involved.
3) In overriding return type must be same.
4) Parameters must be same.
5) Dynamic polymorphism can be acheived using
method overriding.
6) In overriding subclass method hides that of the
superclass method
Example 3: overrde vs overload java
class Dog{
public void bark(){
System.out.println("woof ");
}
}
class Hound extends Dog{
public void sniff(){
System.out.println("sniff ");
}
public void bark(){
System.out.println("bowl");
}
}
public class OverridingTest{
public static void main(String [] args){
Dog dog = new Hound();
dog.bark();
}
}