Java Method Overriding In Hindi

📔 : Java 🔗

parent class में पहले से defined method को child class में define करना ही method overriding कहलाता है।


हम जानते हैं , कि Inheritance से हम किसी class को inherit करके उसकी properties और method को access या use में ले सकते हैं। लेकिन अगर कोई method पहले से base class में present है फिर भी इसकी derived / child class में वो method define कर सकते हैं।

Usage of Method Overriding In java

  1. Method overriding का use , parent class में defined किसी method का child class में proper implementation provide कराने के लिए किया जाता है।

  2. Method overriding का use करके ही run time polymorphism को achieve किया जाता है। हालाँकि इसके बारे में आप आगे पढ़ेंगे।

Java Method Overriding Example

File : Dog.java

CopyFullscreenClose FullscreenRun
class Animal{  
  void eat() {
    System.out.println("An animal is eating...");
  }  
}  

// main class.
public class Dog extends Animal {
  // provide proper implementation for eat() method.
  void eat() {
    System.out.println("The dog is eating...");
  } 
  
  public static void main(String args[]){  
    Dog d = new Dog();  
    d.eat(); 
  }
}
Output
javac Dog.java
java Dog
The dog is eating...

example में , same method को एक new implementation provide किया गया है जो कि parent class में defined method से completely different है।

Access Parent Class's method

जैसा कि आप पहले भी पढ़ चुके हैं कि , किसी class को inherit करने पर उस class के private members को छोड़कर बाकी सभी child class में accessible होते हैं। जिसमे static method को directly कर non static method को this का use करके access कर सकते हैं।


लेकिन method overriding के case में अगर आप this करके method access करोगे तो वहां child class का method call होगा , तो parent class के method override method को access करने के लिए आपको super ही use करना पड़ेगा।
See Example -

File : Dog.java

CopyFullscreenClose FullscreenRun
class Animal{  
  void eat() {
    System.out.println("An animal is eating...");
  }  
}  

// main class.
public class Dog extends Animal {
  void eat() {
    System.out.println("The dog is eating...");
  } 
  
  // define non static method so that we can use this and super.
  void print_action() {
  	this.eat(); // it'll call current class's method.
    super.eat(); // it'll call parent class's method.
  }
  
  public static void main(String args[]){  
    Dog d = new Dog();  
    d.print_action(); 
  }
}
Output
javac Dog.java
java Dog
The dog is eating...
An animal is eating...

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers