Java Method Overriding Tutorial
Method declaration in child class that already present in base class known as overriding method.ex: runtime polymorphism.
Final and Static keyword cannot be overridden.
Constructors cannot be overridden.
Method Overriding Example
class Animal { public void eat() { System.out.println("Generic Animal eating"); } } class Dog extends Animal { public void eat() //eat() method overriden by Dog class. { System.out.println("Dog eat meat"); } }
Method Overloading | Method Overriding |
---|---|
Parameter must be different and name must be same. | Both name and parameter must be same. |
Compile time polymorphism. | Runtime polymorphism. |
Increase readability of code. | Increase reusability of code. |
Access specifier can be changed. | Access specifier cannot be more restrictive than original method(can be less restrictive). |
method overriding Example 2
package com.protutorial.plus; public class Overridingexample { public static void main(String args[]) { Company a = new Company(); // object Company b = new Flipkart(); // object a.address();// runs the method b.address();// Runs the method } } class Company { public void address() { System.out.println(" company Address"); } } class Flipcart extends Company { public void address() { System.out.println("flipkart Address..."); } }