OVERRIDING – Overriding a method means that its
entire functionality is being replaced. Overriding is something done in a child
class to a method defined in a parent class. To override a method a new method
is defined in the child class with exactly the same signature as the one in the
parent class. This has the effect of shadowing the method in the parent class
and the functionality is no longer directly accessible.
Java provides an example of overriding
in the case of the equals method that every class inherits from the granddady
parent Object. The inherited version of equals simply compares where in memory
the instance of the class references. This is often not what is wanted,
particularly in the case of a String. For a string you would generally want to
do a character by character comparison to see if the two strings are the same.
To allow for this the version of equals that comes with String is an overriden
version that performs this character by character comparison. when you extend a
class and write a method in the derived class which is exactly similar to the
one present in the base class, it is termed as overriding.
Example:
public class BaseClass{
public void methodToOverride()
{
//Some code here
}
}
public class DerivedClass extends BaseClass{
public void methodToOverride()
{
//Some new code here
}
}
As
you can see, in the class
DerivedClass, we have overridden the method present in the BaseClass with a
completely new piece of code in the DerivedClass.
What that effectively
means is that if you create an object of DerivedClass and call the
methodToOverride() method, the code in the derivedClass will be executed. If
you hadn’t overridden the method in the DerivedClass then the method in the
BaseClass would have been called.
OVERLOADING - Overloading of methods is a compiler
trick to allow you to use the same name to perform different actions depending
on parameters. when you have more than one method with the same name but
different arguments, the methods are said to be overloaded.
Example:
public class OverLoadingExample{
public void add(int i, int j)
{
int k = i + j;
}
public void add(String s, String t)
{
int k = Integer.parseInt(s) +
Integer.parseInt(t);
}
}
As you can see in the
example above, we have the same method add() taking two parameters but with
different data types. Due to overloading we can now call the add method by
either passing it a String or int .
No comments:
Post a Comment