### Method Overriding in Java
Method overriding is a feature that allows a subclass to provide a specific implementation of a
method that is already defined in its superclass. The method in the subclass has the same
name, parameter list, and return type as the method in the superclass.
#### Rules for Method Overriding:
1. The method in the subclass must have the same method signature (name, parameters, and
return type) as the method in the superclass.
2. The method in the subclass must be at least as accessible (or more accessible) than the
method in the superclass.
3. Constructors and private methods cannot be overridden because they are not inherited.
4. The `@Override` annotation can be used to indicate that a method is intended to override a
superclass method (optional but recommended for clarity).
#### Example of Method Overriding:
```java
// Superclass
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
// Subclass
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal(); // Animal object
Animal dog = new Dog();
// Dog object, but treated as Animal
[Link](); // Output: Animal makes a sound
[Link](); // Output: Dog barks
}
}```
In this example:
- `Animal` class has a `sound()` method.
- `Dog` class extends `Animal` and overrides the `sound()` method with its own
implementation.
- When `[Link]()` is called, Java determines at runtime to invoke `Dog` class's `sound()`
method (dynamic method dispatch).
### `final` Keyword and `super` Keyword in Java
#### `final` Keyword:
The `final` keyword in Java is used to restrict the user from modifying variables, methods, and
classes.
- **Variables:** If a variable is declared as `final`, its value cannot be changed once
initialized.
```java
final int MAX_VALUE = 100;
```
- **Methods:** If a method is declared as `final`, it cannot be overridden by subclasses.
```java
class Parent {
final void display() {
[Link]("Final method");
}
}
```
- **Classes:** If a class is declared as `final`, it cannot be extended (no subclassing).
```java
final class Parent {
// Class contents
}
```
#### `super` Keyword:
The `super` keyword in Java is used to refer to the superclass's variables, methods, and
constructors from within the subclass.
- **Accessing Superclass Variables and Methods:**```java
class Parent {
int num = 10;
void display() {
[Link]("Parent class method");
}
}
class Child extends Parent {
void display() {
[Link]("Child class method");
[Link]("Value of num in parent: " + [Link]);
[Link]();
}
}
```
- **Calling Superclass Constructor:**
```java
class Parent {
Parent() {
[Link]("Parent constructor");
}
}
class Child extends Parent {
Child() {
super(); // Calling parent class constructor
[Link]("Child constructor");
}
}
```