Overriding concept is associated with Inheritance . If we have 2 classes ,one extending the other then child class can override methods of parent class . But there are some rules which needs to be followed :
So we will see which are all these rules :
Rule 1 : The signature of method in the child class should be exactly same as that in Parent class which includes return type, method parameters and name.
Rule 2: Argument list should be exactly same as that of overridden method.
Rule 3: Constructors cannot be overridden .
Rule 4: Static methods cannot be overridden but can be re declared which is actually method hiding .
.
Method Overloading : Overloading in java occurs when methods in a same class or in child classes shares a same name with a ‘difference in number of arguments’ or ‘difference in argument type’ or both.
Argument list could differ in –
Number of parameters
Data type of parameters
Sequence of data type of parameters
You can read in details with example about Method Overloading here.
Method Overloading
|
Method Overriding
|
Signature of method in the child class differs as that in Parent class
|
Signature of method in the child class should be exactly same as that in Parent class
|
Argument list could differ in –
Number of parameters
Data type of parameters
Sequence of data type of parameters
|
Argument list should be exactly same as that of overridden method.
|
Method overloading a single class is it means both of the method are written in the same clas
|
Method overriding we have two classes one is parent other is child .Child class Indane contain the overridden method and it need to extend the parent class .
|
Method overloading is compile time polymorphism.In method overloading if there is an issue with the method signature it is shown in the eclipse as soon as you write the code
|
Method overriding is runtime polymorphism
|
Java Method Overloading example
class javaInHouseOverloadingExample
{
void int add(int a,int b)
{
return a+b;
}
void int add(int a,int b,int c)
{
return a+b+c;
}
}
|
Java Method Overriding example
class Parent
{
void eat()
{
System.out.println("Parent...");
}
}
class Child extends Parent
{
void eat()
{
System.out.println("Child..");
}
}
|
Post a Comment