Overriding in Java

In any item arranged programming language, Overriding is a component that permits a subclass or youngster class to give a particular execution of a strategy that is now given by one of its super-classes or parent classes. At the point when a technique in a subclass has similar name, same boundaries or mark, and same return type(or sub-type) as a strategy in its super-class, then, at that point, the strategy in the subclass is said to abrogate the technique in the super-class.

Technique superseding is one of the way by which java accomplish Run Time Polymorphism.The rendition of a strategy that is executed not entirely settled by the article that is utilized to summon it. Assuming an object of a parent class is utilized to summon the strategy, then, at that point, the rendition in the parent class will be executed, yet in the event that an object of the subclass is utilized to conjure the technique, the adaptation in the youngster class will be executed. All in all, it is the kind of the article being alluded to (not the sort of the reference variable) that figures out which adaptation of an abrogated technique 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()

The superseding strategy should have same return type (or subtype) : From Java 5.0 onwards it is feasible to have different return type for an abrogating technique in kid class, however kid’s return type ought to be sub-sort of parent’s bring type back. This peculiarities is known as covariant bring type back.

Summoning superseded strategy from sub-class : We can call parent class technique in abrogating technique utilizing super catchphrase.

Abrogating and constructor : We would not supersede constructor as parent and youngster be able to class can never have constructor with same name(Constructor name should forever be same as Class name).

// 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();
    }
}
Output:
From parent m2()
From child m2()

Abrogating and Exception-Handling : Below are two guidelines to note while superseding strategies connected with exemption taking care of.

Rule#1 : If the super-class superseded strategy doesn’t toss an exemption, subclass abrogating technique can tosses the unchecked special case, tossing checked exemption will prompt aggregate time mistake.

// 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() {}
}

Output:

13: error: show() in Child cannot override show() in Parent
    void show() {  }
         ^
  overridden method is final
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 the 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();
    }
}
Output:
From parent static m1()
From child non-static(instance) m2()

Rule#2 : If the super-class abrogated technique does tosses an exemption, subclass superseding strategy can toss same, subclass special case. Tossing guardian special case in Exception ordered progression will prompt assemble time error.Also there is no issue in the event that subclass superseded technique isn’t tossing any exemption.

Abrogating and conceptual technique: Abstract strategies in a point of interaction or dynamic class are intended to be superseded in determined substantial classes in any case an incorporate time mistake will be tossed.

// 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();
    }
}
Output:
Parent's show()
Child's show()

Rules for strategy abrogating:

Superseding and Access-Modifiers : The entrance modifier for an abrogating technique can permit more, yet not less, access than the abrogated strategy. For instance, an ensured example technique in the super-class can be unveiled, however not private, in the subclass. Doing as such, will produce aggregate time mistake.

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

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

Last strategies can not be abrogated: If we don’t need a strategy to be superseded, we pronounce it as last. Kindly see Using last with Inheritance.

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

Output:

error: m1() in Child4 cannot override m1() in Parent
    void m1() throws Exception
         ^
  overridden method does not throw Exception

Static strategies can not be overridden(Method Overriding versus Method Hiding): When you characterize a static strategy with same signature as a static technique in base class, it is known as technique stowing away.

The accompanying table sums up what happens when you characterize a technique with a similar signature as a strategy in a super-class.

// 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 salary() of Parent
    int salary()
    {
        return base + 20000;
    }
}
 
// Inherited class
class Clerk extends Employee {
    // This method overrides salary() of Parent
    int salary()
    {
        return base + 10000;
    }
}
 
// Driver class
class Main {
    // This method can be used to print the salary of
    // any type of employee using base class reference
    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);
    }
}
Output:
Manager's salary : 30000
Clerk's salary : 20000

Also Read: How to Install Minecraft on Linux?

Leave a Reply

Your email address will not be published.