Method Overriding in Java

Method Overriding in Java

Method Overriding in Java

When a method in a subclass has the same name, the same parameter(s), and the same return type (or its sub-type) as its super-class, then the method in the subclass is called override method and in super class (parent class) it is called overridden  method. This concept is known as Method Overrding.

Method overriding in Java is a concept in object-oriented programming that allows a subclass to provide a specific implementation for a method that is already defined in its superclass.

In other words, when a super class has a method(s) and sub class inherits that method(s) with the same name, return type, and parameter(s), can provide its own specialized implementation. This allows the subclass to customize or extend the behavior of the method.

class Superclass {
	void methodToOverride() {
    	// Original method implementation
	}
}
 
class Subclass extends Superclass {
   @Override
	void methodToOverride() {
    	// New implementation for the overridden method
	}
}

Usage of Method Overriding

1. It gives subclasses to provide their own specific implementations. This is particularly useful when you have a general method in a superclass, and you want to give specific customized behavior in its subclasses.

2. Method overriding enables polymorphism and dynamic binding. When you have a method that’s overridden in multiple subclasses. Which method will be invoked, it is decided at run time on the basis of type of object creation.

3. Useful in Extending and Specialized behaviour. By defining common methods in a superclass and allowing subclasses to override them for specific behaviour. This leads to cleaner and more maintainable codebase.

4. It promotes Code reusability. Using Overriding concept, you can avoid duplication of code by writing common methods in superclass and specialized functionality in its subclasses.

Rules of Method Overriding

1. Method Signature Matching: The overridden method in the subclass must have the same method signature as the method in the superclass. Any deviation will result in a compilation error. Method signature means method name, parameter(s) and return type (subtype). Method modifier either be same or higher. Method access modifier cannot be narrow down. It is because If a subclass method had more restrictive access, it would not be able to fulfill ‘Liskov Substitution Principle’ principle. It would limit the behavior that the base class method provides.

Example :  
 
public  class TestSuperClass {
   	public void testSuperClassOverrideMethod() {
          	System.out.println("In Superclass method!!");
   	}
  }
 
public class TestSubClass extends TestSuperClass{
   	protected void testSuperClassOverrideMethod() {
   	   	System.out.println("In TestSubClass method!!");
   	}
}
 

2. Return Type: return type of the overriding method can be a subtype (subclass) of the return type of the overridden method in the superclass. This allows for a more specific return type in the subclass without breaking compatibility with the superclass. But in case of primitive data types (e.g., int, double, char), the return types must be exactly the same between the overridden method and the overriding method.

For example, if a superclass method returns a type Animal, a subclass method override it and return a more specific type, like Dog or ca

class Animal {
    Animal makeSound() {
        return new Animal();
    }
}


class Dog extends Animal {
    @Override
    Dog makeSound() {
        return new Dog();
    }
}

3. Access Modifier Constraints: The access modifier of the overriding method cannot be more restrictive than that of the overridden method. Either It can be equally accessible or more accessible. e.g. if a method in super classs is having protected modifier than in subclass either it could be same as protected or public (higher accessmodifier).

Example: Compilation error due to restrictive modifier in override method of subclass:

If you will try to  reduce method accessibility modifier in subclass, you will experience compile time error likeCannot reduce the visibility of the inherited method from TestSuperClass”

public  class TestSuperClass {
          	
protected void testSuperClassOverrideMethod() {
          	System.out.println("In Superclass method!!");
   	}
   	
}
 
public class TestSubClass extends TestSuperClass{
   	void testSuperClassOverrideMethod() {   // default modifier
          	System.out.println("In TestSubClass method!!");
   	}
  }
 
Example : Higher the access modifier in subclass method.

public  class TestSuperClass {
          	protected void testSuperClassOverrideMethod() {
          	System.out.println("In Superclass method!!");
   	}	
}
 
public class TestSubClass extends TestSuperClass{
   	public void testSuperClassOverrideMethod() {
          	System.out.println("In TestSubClass method!!");
   	}
   	
}

4. final Method : final method can not be overridden in subclass as final  method means that the method’s implementation in that class is considered complete and cannot be further modified or extended by subclasses.

5. Private Methods: Methods marked as private in the superclass cannot be overridden in subclasses. As private keyword restricts the visibility within the class only.

6. Static Methods: Static methods are bound to the class and not to the instance that is why static methods cannot be override. Only instance methods can be overridden.

 7. Constructor: Constructors are specific to class and called to create instance of a class. Constructor overriding is not possible. Subclass can call super class constructor by super() method.

Example :
public class TestSuperClass {
    	public TestSuperClass() {
          	System.out.println("In TestSuperClass constructor" );
   	}
}
 
public class TestSubClass extends TestSuperClass {
	public TestSubClass() {
		super();
      	System.out.println("In  TestSubClass constructor constructor");
	}
}

8. Superclass Method Invocation: The overriding method in the subclass can call the overridden method in the superclass using the super keyword. This allows developers to extend the functionality of the superclass method while leveraging its existing logic.

public class TestSuperClass {
    	public void testSuperClassOverrideMethod() {
          	System.out.println("In Superclass method!!");
   	}
}
 
public class TestSubClass extends TestSuperClass {
    	public void testSuperClassOverrideMethod() {
          		super.testSuperClassOverrideMethod();
          		System.out.println("In TestSubClass method!!");
   	}
}

Method Override Example

We want to calculate the area of any geometric shape like Circle, Rectangle etc. for that we will create a class Shape which is having methods calculateArea()  and printCalulatedArea(). To extend the functionality to calculateArea of other shapes like Circle, Rectangle etc, can extend the Shape class and write its logic to calculate area.

Benefit of the approach is you can calculate the area of any shape as per creating the instance of the respective class. 

Superclass: Shape 

public class Shape {

	public double calculatedArea;

	public void calculateArea() {
		System.out.println("calculate Area  "); // Default implementation for a general shape
	}

	public void printCalulatedArea() {
		System.out.println("Calculated area is " + calculatedArea);
	}
}


Subclass: Circle

public class Circle extends Shape {
	private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public void calculateArea() {
        calculatedArea = Math.PI * radius * radius; // Area of a circle
        super.printCalulatedArea();
    }
}


Subclass: Rectangle

public class Rectangle  extends Shape {
    private double width;
    private double height;

    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public void calculateArea() {
        calculatedArea = width * height; // Area of a rectangle
        super.printCalulatedArea();
    }
}

Exception Handling Rule in Overriding

Exception handling rules in method overriding in Java are designed to maintain the safety and predictability of the code while adhering to the principles of the language. Here’s what you need to know about exception handling rules when overriding methods:

  1.  If a superclass method does not throw any exception 
  • The overriding method  in subclass can throw any unchecked or runtime exception.
  • The overriding method in subclass can not throw any checked or compile-time exception.
  1. If an overridden method throws an unchecked or runtime exception 
  • The overriding method can throw any runtime exception or the same exception as thrown by the overridden method.
  • The overriding method can ignore the method level exception.
  1.  If the superclass method throws checked or compile-time exception 
  • overriding methods in subclass can throw same type of checked exception or one of its sub-class or no exception
  • Subclass method cannot throw the exception which is a superclass of the overridden method.
  • Subclass method can throw any unchecked or runtime exception.

Difference Between Method Overriding and Method Overloading

AspectMethod OverridingMethod Overloading
DefinitionOverriding is related to super class and subclass relationships. Same name method(s) with same parameter(s) and return type in the child class.Same name methods with different parameter(s) in the same class.
Inheritance RequiredIt requires inheritance. Involves a superclass-subclass relationship.Not dependent on inheritance. Can be applied to a single class.
Method SignatureMethod names, parameter types, and return types must be identified in child class as in parent class.Method names are the same, but parameter types or numbers of parameters can be different.
BindingResolved at runtime (dynamic binding) based on the actual object type.Resolved at compile time (static binding) based on method signature.
Use CaseUsed to specialize and customize behavior of inherited methods in subclasses.Used for creating multiple methods for different parameter scenarios in a single class.
Examplejava class Shape { void draw() { System.out.println(“Drawing a shape”); } } class Circle extends Shape { @Override void draw() { System.out.println(“Drawing a circle”); } }java class Calculator { int sum(int a, int b) { return a + b; } double sum(double a, double b) { return a + b; } }

Conclusion

Method overriding is a powerful tool in the Java programming which enables customization, polymorphism, and code reuse. By allowing subclasses to redefine inherited methods, Java facilitates the creation of complex class into simple, understandable and respective behavioural functional class. This reduce the code duplicity and this dynamic interplay between superclass and subclass methods underpins the foundation of flexible and maintainable software design. Mastery of method overriding is not only a badge of expertise but also a witness to a developer’s ability to join Java’s object-oriented proficiency.

P.S. We welcome your feedback. Please comment, if you find anything incorrect, or want to share more information about the topic or want to share any kind of feedback.

Leave a Reply

Your email address will not be published. Required fields are marked *