пятница, 5 января 2024 г.

Method Overriding in Java

    Method overriding in Java is a concept that allows a subclass to provide a specific implementation for a method that is already defined in its superclass. This enables a subclass to provide a specialized version of a method that is already defined in its superclass. Method overriding is a key feature of object-oriented programming and facilitates polymorphism.

Here are the key points to understand about method overriding in Java:

    • Inheritance: Method overriding is closely tied to inheritance. The method that is to be overridden must be defined in the superclass and inherited by the subclass.
    • Method Signature: The overriding method in the subclass must have the same method signature (name, return type, and parameter types) as the method in the superclass.
    • Access Modifiers: The access level of the overriding method in the subclass should be the same as or more accessible than the overridden method in the superclass. For example, if the superclass method is declared as protected, the overriding method in the subclass can be protected or public, but not private.
    • Return Type: The return type of the overriding method in the subclass must be the same as or a subtype of the return type of the overridden method in the superclass. In Java 5 and later versions, covariant return types allow the return type to be a subtype.
    • Exception Handling: The overriding method is allowed to throw the same, narrower, or no exceptions as the overridden method. However, it is not allowed to throw broader exceptions.
class Animal {
void makeSound() {
System.out.println("Some generic sound");
}
}

class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow");
}
}

public class Main {
public static void main(String[] args) {
Animal animal = new Cat(); // Polymorphism
animal.makeSound(); // Calls the overridden method in Cat
}
}

Комментариев нет:

Отправить комментарий