Method Overriding in Java with Example

Description :
Method overriding in java means a subclass method overriding a super class method. Superclass method should be non-static. Subclass uses extends keyword to extend the super class. In the example class B is is the sub class and class A is the super class. In overriding methods of both subclass and superclass possess same signatures. Overriding is used in modifying  the methods of the super class. In overriding  return types and constructor parameters of methods should match .

Another way of explanation:
In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden

Method Overriding is achieved when a subclass overrides non-static methods defined in the superclass, following which the new method implementation in the subclass that is executed.

The new method definition must have the same method signature (i.e., method name and parameters) and return type. Only parameter types and return type are chosen as criteria for matching method signature. So if a subclass has its method parameters as final it doesn’t really matter for method overriding scenarios as it still holds true. The new method definition cannot narrow the accessibility of the method, but it can widen it. The new method definition can only specify all or none, or a subset of the exception classes (including their subclasses) specified in the throws clause of the overridden method in the super class

// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
// display i and j
void test() {
System.out.println("i and j: " + i + " " + j);

class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
// display k – this overrides test() in A
void test() {
System.out.println("k: " + k);

class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.test(); // this calls test() in B
The output produced by this program is testn here:

k: 3

When test( ) is invoked on an object of type B, the version of test( ) defined within B is used. That is, the versio n of test( ) inside B overrides the version declared in A. If you wish to access the superclass version of an overridden function, you can do so by using super. For example, in this version of B, the superclass version of test( ) is invoked within the subclass' version. This allows all instance variables to be displayed.

No comments:

Post a Comment

Please Provide your feedback here