Method overriding in java. In English
Method Overriding
A method that is already given by one of a subclass's super-classes or parent classes can be specifically implemented by a subclass or child class in Java by using a feature called overriding. It is said that a method in a subclass "override" a method in the superclass when both methods share the same name, the same parameters or signature, and the same return type.
One way Java implements Run Time Polymorphism is by method overriding. The object that is used to invoke a method will determine which version of it is executed. If a method is invoked by an object of a parent class, the method in the parent class will be utilized; however, if a method is invoked by an object of a subclass, the method in the child class will be used. To put it another way, the type of the object being referenced decides which override method will be called, not the type of the reference variable.
Rules for method overriding...............
- Java only allows for the writing of methods in child classes, never in the same class.
- The argument list must match that of the class's overridden method.
- If an instance method is inherited by the child class, it can also be overridden.
- There is no way to override a constructor.
- Declared methods that are final cannot be overridden.
- There is no way to override a static method.
- The return type must match the return type stated in the original overridden method in the parent class or be a subtype of that type.
- It is not possible to override a method if it cannot be inherited.
- Any parent class method that is not marked as private or final may be overridden by a child class belonging to the same package as the instance's parent class.
- Only non-final methods that have been marked as public or protected may be overridden by a child class in a separate package.
Example: -
class School {
public void change () {
System.out.println("School is open");
}
}
class University extends School {
public void change () {
System.out.println("University is open too");
}
}
class student {
public static void main(String args[]) {
School a = new School ();
School b = new University ();
a.change();
b.change();
}
}
Output - School is open
University is open too
Different between method overloading and method overriding in java
class Overloading {
static int add (int a, int b) {
return a + b;
}
static int add (int a, int b, int c) {
return a +b +c;
}
}
Method overriding Example: -
class Animal {
void eat () {
System.out.println("Drinking");
}
}
class Cat extends Animal {
void eat () {
System.out.println("Drinking Milk");
}
}
Comments
Post a Comment