Showing posts with label Method Overriding. Show all posts
Showing posts with label Method Overriding. Show all posts

Jul 5, 2020

Method Overriding in JAVA | Java Language | Coding Winds

METHOD OVERRIDING

Hello guys, today we are here with another blog and we are going to talk about method overriding. Method overriding is a simple implementation where we can reuse a method in a subclass, with some updated code. In simple words, we can override a method which is used in a class (parent or base class), again in it's subclass with some different or updated code as required. So let's see a simple example of method overriding.

Ex:

import java.util.*;

class sample {

     void myMethod() {

         System.out.println("Hello Readers!");

     }

}

class sample2 extends sample {

     void myMethod() {

         System.out.println("Hello Coders!");

     }

}

public class Coding_Winds {

     public static void main(String[] args) {

     sample obj = new sample();

     sample2 obj2 = new sample2();

     obj.myMethod();

     obj2.myMethod();

     }

}

/*Output: Hello Readers!

  Hello Coders!

*/

So the output will be according to the objects used for calling the classes accordingly. Now an example is given below which shows what can be a situation where methods overriding is actually appropriate.

Ex:

class Dollars {

     void myCurrency() {

         System.out.println("100 American cents make 1 US Dollar");

     }

}

class Euros extends Dollars{

     void myCurrency() {

         System.out.println("0.89 Euros make 1 Dollar");

     }

}

class Rupees extends Dollars{

     void myCurrency() {

         System.out.println("75.54 Rupees make 1 Dollar");

     }

}

public class Coding_Winds {

     public static void main(String[] args) {

     Dollars d = new Dollars();

     Euros e = new Euros();

     Rupees r = new Rupees();

     d.myCurrency();

     e.myCurrency();

     r.myCurrency();

     }

}/*Output: 100 American cents make 1 US Dollar

0.89 Euros make 1 Dollar

75.54 Rupees make 1 Dollar */

 

The example above has a parent class 'Dollars' with a method ('myMethod') which is used by all the subclasses of the parent class 'Dollars', but with different print statements . And any particular method can be called in the main method by using the objects for that class which contains that particular method.



Hope you are clear on this  topic do read our more articles on JAVA LANGUAGE.


If you still have any doubt on this topic then do come to us via email "sophomoretechs@gmail.com" or via Instagram "@coding.winds".


This article is SUBMITTED By : Pranjal Rai


Do subscribe to our daily blog update by clicking here.


Thank You!