[go: up one dir, main page]

0% found this document useful (0 votes)
52 views19 pages

Methods-Overload Override

The document discusses method overloading in Java. It provides examples of overloading methods by changing the number and type of parameters. Method overloading allows creating multiple methods with the same name but different signatures. This increases readability by avoiding confusing names for methods that perform similar tasks with different parameters. The key points are that method overloading is done by changing parameters but not return types, and overloaded methods must have unique parameter lists.

Uploaded by

siddhant kudesia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views19 pages

Methods-Overload Override

The document discusses method overloading in Java. It provides examples of overloading methods by changing the number and type of parameters. Method overloading allows creating multiple methods with the same name but different signatures. This increases readability by avoiding confusing names for methods that perform similar tasks with different parameters. The key points are that method overloading is done by changing parameters but not return types, and overloaded methods must have unique parameter lists.

Uploaded by

siddhant kudesia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

n Java, two or more 

methods can have same name if they differ in parameters


(different number of parameters, different types of parameters, or both). These
methods are called overloaded methods and this feature is called method
overloading. For example:

void func() { ... }

void func(int a) { ... }

float func(double a) { ... }

float func(int a, float b) { ... }

Here, func() method is overloaded. These methods have same name but accept


different arguments.

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.

Why method overloading?


Suppose, you have to perform addition of the given numbers but there can be any
number of arguments (let’s say either 2 or 3 arguments for simplicity).

In order to accomplish the task, you can create two methods sum2num(int,


int) and sum3num(int, int, int) for two and three parameters respectively.
However, other programmers as well as you in future may get confused as the
behavior of both methods is same but they differ by name.

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.

How to perform method overloading in


Java?
Here are different ways to perform method overloading:
1. Overloading by changing number of arguments

class MethodOverloading {
private static void display(int a){
System.out.println("Arguments: " + a);
}

private static void display(int a, int b){


System.out.println("Arguments: " + a + " and " + b);
}

public static void main(String[] args) {


display(1);
display(1, 4);
}
}

When you run the program, the output will be:

Arguments: 1

Arguments: 1 and 4
2. By changing the datatype of parameters

class MethodOverloading {

// this method accepts int


private static void display(int a){
System.out.println("Got Integer data.");
}

// this method accepts String object


private static void display(String a){
System.out.println("Got String object.");
}

public static void main(String[] args) {


display(1);
display("Hello");
}
}

When you run the program, the output will be:

Got Integer data.

Got String object.

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 {

private String formatNumber(int value) {


return String.format("%d", value);
}
private String formatNumber(double value) {
return String.format("%.3f", value);
} private String formatNumber(String value) {

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"));
}
}

When you run the program, the output will be:

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.

Method overriding is one of the way by which java achieve Run Time


Polymorphism.The version of a method that is executed will be determined by the
object that is used to invoke it. If an object of a parent class is used to invoke the
method, then the version in the parent class will be executed, but if an object of the
subclass is used to invoke the method, then the version in the child class will be
executed.In other words, it is the type of the object being referred to (not the type of
the reference variable) that determines which version of an overridden method will
be executed.
// A Simple Java program to demonstrate
// method overriding in java
 
// 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() { System.out.println("Child's show()"); }
}
 
// Driver class
class Main
{
    public static void main(String[] args)
    {
        // If a Parent type reference refers
        // to a Parent object, then Parent's
        // show is called
        Parent obj1 = new Parent();
        obj1.show();
 
        // If a Parent type reference refers
        // to a Child object Child's show()
        // is called. This is called RUN TIME
        // POLYMORPHISM.
        Parent obj2 = new Child();
        obj2.show();
    }
}
Output:

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 :

4. From parent m2()

5. From child m2()

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 :

9. 13: error: show() in Child cannot override show() in Parent

10. void show() { }

11. ^

12. overridden method is final

13. Static methods can not be overridden(Method Overriding vs Method


Hiding) : When you defines a static method with same signature as a static method in base
class, it is known as method hiding.
The following table summarizes what happens when you define a method with the same
signature as a method in a super-class.

  SUPERCLASS INSTANCE METHOD SUPERCLASS STATIC METHOD

SUBCLASS INSTANCE METHOD Overrides Generates a compile-time error

SUBCLASS STATIC METHOD Generates a compile-time error Hides

/* Java program to show that if static method is redefined by


a derived class, then it is not overriding,it is hiding */
 
class Parent
{
    // Static method in base class which will be hidden in subclass
    static void m1() { System.out.println("From parent static m1()");}
     
    // Non-static method which will be overridden in derived class
    void m2() { System.out.println("From parent non-static(instance) m2()"); }
}
 
class Child extends Parent
{
    // This method hides m1() in Parent
    static void m1() { System.out.println("From child static m1()");}
     
    // This method overrides m2() in Parent
    @Override
    public void m2() { System.out.println("From child non-static(instance) m2()");}
     
}
 
// Driver class
class Main
{
    public static void main(String[] args)
    {
        Parent obj1 = new Child();
         
        // As per overriding rules this should call to class Child static
        // overridden method. Since static method can not be overridden, it
        // calls Parent's m1()
        obj1.m1();
     
        // Here overriding works and Child's m2() is called
        obj1.m2();
    }
}
Run on IDE
Output :

From parent static m1()

From child non-static(instance) m2()

14. Private methods can not be overridden : Private methods cannot be overridden as


they are bonded during compile time. Therefore we can’t even override private methods in a
subclass.(See this for details).
 

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:

19. Parent's show()

20. Child's show()

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:

 error: m2() in Child cannot override m2() in Parent


 void m2() throws Exception{ System.out.println("From child m2");}
 ^

 overridden method does not throw Exception

 Rule#2 : If the super-class overridden method does throws an exception,


subclass overriding method can only throw same, subclass exception.
Throwing parent exception in Exception hierarchy will lead to compile time
error.Also there is no issue if subclass overridden method is not throwing any
exception.
/* Java program to demonstrate overriding when
  superclass method does declare an exception
*/
 
class Parent
{
    void m1() throws RuntimeException
    { System.out.println("From parent m1()");}
     
}
 
class Child1 extends Parent
{
    @Override
    // no issue while throwing same exception
    void m1() throws RuntimeException
    { System.out.println("From child1 m1()");}
     
}
class Child2 extends Parent
{
    @Override
    // no issue while throwing subclass exception
    void m1() throws ArithmeticException
    { System.out.println("From child2 m1()");}
     
}
class Child3 extends Parent
{
    @Override
    // no issue while not throwing any exception
    void m1()
    { System.out.println("From child3 m1()");}
     
}
class Child4 extends Parent
{
    @Override
    // compile-time error
    // issue while throwing parent exception
    void m1() throws Exception
    { System.out.println("From child4 m1()");}
     
}
 Run on IDE
 Output:
 error: m1() in Child4 cannot override m1() in Parent
 void m1() throws Exception

 ^

 overridden method does not throw Exception

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.
 

24. Overriding and synchronized/stricfp method : The presence of synchronized/stricfp


modifier with method have no effect on the rules of overriding, i.e. it’s possible that a
synchronized/stricfp method can override a non synchronized/stricfp one and vice-versa.
Note :
1. In C++, we need virtual keyword to achieve overriding or Run Time Polymorphism. In
Java, methods are virtual by default.
2. We can have multilevel method-overriding.
// A Java program to demonstrate
//  multi-level overriding
 
// Base Class
class Parent
{
    void show() { System.out.println("Parent's show()"); }
}
 
// Inherited class
class Child extends Parent
{
    // This method overrides show() of Parent
    void show() { System.out.println("Child's show()"); }
}
 
// Inherited class
class GrandChild extends Child
{
    // This method overrides show() of Parent
    void show() { System.out.println("GrandChild's show()"); }
}
 
// Driver class
class Main
{
    public static void main(String[] args)
    {
        Parent obj1 = new GrandChild();
        obj1.show();
    }
}
3. Run on IDE
4. Output :

5. GrandChild's show()
6. Overriding vs Overloading :

1. Overloading is about same method have different signatures. Overriding is


about same method, same signature but different classes connected through
inheritance.

2. Overloading is an example of compiler-time polymorphism and overriding is


an example of run time polymorphism.
 
Why Method Overriding ?
As stated earlier, overridden methods allow Java to support run-time polymorphism.
Polymorphism is essential to object-oriented programming for one reason: it allows a
general class to specify methods that will be common to all of its derivatives, while
allowing subclasses to define the specific implementation of some or all of those
methods.Overridden methods are another way that Java implements the “one
interface, multiple methods” aspect of polymorphism.
Dynamic Method Dispatch is one of the most powerful mechanisms that object
oriented design brings to bear on code reuse and robustness. The ability of existing
code libraries to call methods on instances of new classes without recompiling while
maintaining a clean abstract interface is a profoundly powerful tool.
Overridden methods allow us to call methods of any of the derived classes without
even knowing type of derived class object.
 
When to apply Method Overriding ?(with example)
Overriding and Inheritance : Part of the key to successfully applying polymorphism
is understanding that the superclasses and subclasses form a hierarchy which
moves from lesser to greaterspecialization. Used correctly, the superclass provides
all elements that a subclass can use directly. It also defines those methods that the
derived class must implement on its own. This allows the subclass the flexibility to
define its own methods, yet still enforces a consistent interface. Thus, by combining
inheritance with overridden methods, a superclass can define the general form of
the methods that will be used by all of its subclasses.
Let’s look at a more practical example that uses method overriding. Consider a
employee management software for an organization, let the code has a simple base
class Employee, the class has methods like raiseSalary(), transfer(), promote(),.. etc.
Different types of employees like Manager, Engineer, ..etc may have their own
implementations of the methods present in base class Employee. In our complete
software, we just need to pass a list of employees everywhere and call appropriate
methods without even knowing the type of employee. For example, we can easily
raise salary of all employees by iterating through list of employees. Every type of
employee may have its own logic in its class, we don’t need to worry because if
raiseSalary() is present for a specific employee type, only that method would be
called.

// A Simple Java program to demonstrate application


// of overriding in Java
 
// Base Class
class Employee
{
    public static int base = 10000;
    int salary()
    {
        return base;
    }
}
 
// Inherited class
class Manager extends Employee
{
    // This method overrides show() of Parent
    int salary()
    {
        return base + 20000;
    }
}
 
// Inherited class
class Clerk extends Employee
{
    // This method overrides show() of Parent
    int salary()
    {
        return base + 10000;
    }
}
 
// Driver class
class Main
{
    // This method can be used to print salary of
    // any type of employee using base class refernce
    static void printSalary(Employee e)
    {
        System.out.println(e.salary());
    }
 
    public static void main(String[] args)
    {
        Employee obj1 = new Manager();
 
        // We could also get type of employee using
        // one more overridden method.loke getType()
        System.out.print("Manager's salary : ");
        printSalary(obj1);
 
        Employee obj2 = new Clerk();
        System.out.print("Clerk's salary : ");
        printSalary(obj2);
    }
}
Run on IDE
Output:

Manager's salary : 30000

Clerk's salary : 20000

What is Static Variable in Java?


Static variable in Java is variable which belongs to the class and initialized only
once at the start of the execution.

 It is a variable which belongs to the class and not to object(instance)


 Static variables are initialized only once, at the start of the execution.
These variables will be initialized first, before the initialization of any
instance variables
 A single copy to be shared by all instances of the class
 A static variable can be accessed directly by the class name and doesn’t
need any object
Syntax :

<class-name>.<variable-name>

What is Static Method in Java?


Static method in Java is a method which belongs to the class and not to the
object. A static method can access only static data.

 It is a method which belongs to the class and not to the object(instance)


 A static method can access only static data. It can not access non-static
data (instance variables)
 A static method can call only other static methods and can not call a non-
static method from it.
 A static method can be accessed directly by the class name and doesn’t
need any object
 A static method cannot refer to "this" or "super" keywords in anyway

Syntax :

<class-name>.<method-name>

Example: How to call static variables & methods

Step 1) Copy the following code into a editor

public class Demo{


public static void main(String args[]){
Student s1 = new Student();
s1.showData();
Student s2 = new Student();
s2.showData();
//Student.b++;
//s1.showData();
}
}
class Student {
int a; //initialized to zero
static int b; //initialized to zero only when class is loaded not for each object
created.

Student(){
//Constructor incrementing static variable b
b++;
}

public void showData(){


System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
}
//public static void increment(){
//a++;
//}

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.

error: non-static variable a cannot be referenced from a static context


a++;

Step 6) Error = ? This is because it is not possible to access instance variable "a"
from java static class method "increment".

You might also like