Method Overriding in Java

 In Java, method overriding allows a subclass to provide its own implementation of a method that is already defined in its superclass. This means that when the method is called on an instance of the subclass, the subclass's implementation will be executed instead of the superclass's implementation.

To override a method in Java, the following rules must be followed:

  1. The method in the subclass must have the same name, return type, and parameters as the method in the superclass that it is overriding.

  2. The access level of the overriding method cannot be more restrictive than the access level of the overridden method. For example, if the overridden method is public, the overriding method must also be public or protected, but not private.

  3. The overriding method can throw any unchecked exceptions, but it must not throw any checked exceptions that are not declared in the overridden method's throws clause.

Here is an example of method overriding in Java:

mohit

class Animal 

public void makeSound() 

 System.out.println("The animal makes a sound"); 
 } 

class Cat extends Animal 

public void makeSound() 

 System.out.println("Meow");


public class Main 

public static void main(String[] args) 

 Animal animal = new Animal(); animal.makeSound(); Cat cat = new Cat(); cat.makeSound(); 
 } 
}

In this example, the Cat class extends the Animal class and overrides the makeSound() method. When the makeSound() method is called on an instance of Cat, the Cat class's implementation will be executed instead of the Animal class's implementation

Comments

Popular posts from this blog

Cryptography API

Java Applet Overview

Vector in Java