Methods-Overload Override
Methods-Overload Override
Notice that, the return type of these methods are not same. Overloaded methods
may or may not have different return type, but they must differ in parameters they
accept.
The better way to accomplish this task is by overloading methods. And, depending
upon the argument passed, one of the overloaded methods is called. This helps to
increase readability of the program.
class MethodOverloading {
private static void display(int a){
System.out.println("Arguments: " + a);
}
Arguments: 1
Arguments: 1 and 4
2. By changing the datatype of parameters
class MethodOverloading {
Here, both overloaded methods accept one argument. However, one accepts
argument of type int whereas other accepts String object.
Let’s look at a real world example:
class HelperService {
return String.format("%.2f",
Double.parseDouble(value));
}
public static void main(String[] args) {
HelperService hs = new HelperService();
System.out.println(hs.formatNumber(500));
System.out.println(hs.formatNumber(89.9934));
System.out.println(hs.formatNumber("550"));
}
}
500
89.993
550.00
Important Points
Two or more methods can have same name inside the same class if they
accept different arguments. This feature is known as method overloading.
Method overloading is achieved by either:
o changing the number of arguments.
o or changing the datatype of arguments.
Method overloading is not possible by changing the return type of methods.
( The compiler does not consider the return type while differentiating
the overloaded method. But you cannot declare two methods with the same
signature and differentreturn type. It will throw a compile-time error. If
both methods have the same parameter types, but different return type,
then it is not possible.)
Overriding in Java
In any object-oriented programming language, Overriding is a feature that allows a
subclass or child class to provide a specific implementation of a method that is
already provided by one of its super-classes or parent classes. When a method in a
subclass has the same name, same parameters or signature and same return
type(or sub-type) as a method in its super-class, then the method in the
subclass is said to override the method in the super-class.
Parent's show()
Child's show()
Rules for method overriding:
1. Overriding and Access-Modifiers : The access modifier for an overriding method can
allow more, but not less, access than the overridden method. For example, a protected instance
method in the super-class can be made public, but not private, in the subclass. Doing so, will
generate compile-time error.
// A Simple Java program to demonstrate
// Overriding and Access-Modifiers
class Parent
{
// private methods are not overridden
private void m1() { System.out.println("From parent m1()");}
protected void m2() { System.out.println("From parent m2()"); }
}
class Child extends Parent
{
// new m1() method
// unique to Child class
private void m1() { System.out.println("From child m1()");}
// overriding method
// with more accessibility
@Override
public void m2() { System.out.println("From child m2()");}
}
// Driver class
class Main
{
public static void main(String[] args)
{
Parent obj1 = new Parent();
obj1.m2();
Parent obj2 = new Child();
obj2.m2();
}
}
2. Run on IDE
3. Output :
6. Final methods can not be overridden : If we don’t want a method to be overridden, we
declare it as final. Please see Using final with Inheritance .
// A Java program to demonstrate that
// final methods cannot be overridden
class Parent
{
// Can't be overridden
final void show() { }
}
class Child extends Parent
{
// This would produce error
void show() { }
}
7. Run on IDE
8. Output :
11. ^
15. The overriding method must have same return type (or subtype) : From Java 5.0
onwards it is possible to have different return type for a overriding method in child class, but
child’s return type should be sub-type of parent’s return type. This phenomena is known
as covariant return type.
16. Invoking overridden method from sub-class : We can call parent class method in
overriding method using super keyword.
// A Java program to demonstrate that overridden
// method can be called from sub-class
// Base Class
class Parent
{
void show()
{
System.out.println("Parent's show()");
}
}
// Inherited class
class Child extends Parent
{
// This method overrides show() of Parent
@Override
void show()
{
super.show();
System.out.println("Child's show()");
}
}
// Driver class
class Main
{
public static void main(String[] args)
{
Parent obj = new Child();
obj.show();
}
}
17. Run on IDE
18. Output:
21. Overriding and constructor : We can not override constructor as parent and child class
can never have constructor with same name(Constructor name must always be same as Class
name).
22. Overriding and Exception-Handling : Below are two rules to note when overriding
methods related to exception-handling.
Rule#1 : If the super-class overridden method does not throws an exception,
subclass overriding method can only throws the unchecked exception,
throwing checked exception will lead to compile-time error.
/* Java program to demonstrate overriding when
superclass method does not declare an exception
*/
class Parent
{
void m1() { System.out.println("From parent m1()");}
void m2() { System.out.println("From parent m2()"); }
}
class Child extends Parent
{
@Override
// no issue while throwing unchecked exception
void m1() throws ArithmeticException
{ System.out.println("From child m1()");}
@Override
// compile-time error
// issue while throwin checked exception
void m2() throws Exception{ System.out.println("From child m2");}
}
Run on IDE
Output:
^
23. Overriding and abstract method : Abstract methods in an interface or abstract class are
meant to be overridden in derived concrete classes otherwise compile-time error will be thrown.
5. GrandChild's show()
6. Overriding vs Overloading :
<class-name>.<variable-name>
Syntax :
<class-name>.<method-name>
Student(){
//Constructor incrementing static variable b
b++;
}
Following diagram shows, how reference variables & objects are created and
static variables are accessed by the different instances.
Step 4) It is possible to access a static variable from outside the class using the
syntax ClassName.Variable_Name. Uncomment line # 7 & 8 . Save , Compile &
Run . Observe the output.
Value of a = 0
Value of b = 1
Value of a = 0
Value of b = 2
Value of a = 0
Value of b = 3
Step 5) Uncomment line 25,26 & 27 . Save , Compile & Run.
Step 6) Error = ? This is because it is not possible to access instance variable "a"
from java static class method "increment".