Java Polymorphism In Hindi

📔 : Java 🔗

Polymorphism का अर्थ है many forms , यह यह एक geek भाषा का शब्द है दो शब्दों में मिलकर बना हुआ है poly(many) और morph(forms) . सरल शब्दों में कहें तो , polymorphism का मतलब है many forms।


Polymorphism एक ability है जिसके द्वारा एक तरह के resources को आप different - different तरीके से access कर सकते हैं। इस concept को normally Inheritance में use किया जाता है।

Java Polymorphism Types

polymorphism को दो तरह से को achieve किया जाता है -

  1. Run Time Polymorphism
  2. Compile Time Polymorphism

Java Compile Time Polymorphism

इस प्रकार के polymorphism को Method Overloading / Operator Overloading के द्वारा achieve किया जाता है। इसे static या Early Binding भी कहते हैं क्योंकि इसमें parameter compile time bind होते हैं। Overloaded Methods को pass किये गए arguments की संख्या के according compile time में invoke किया जाता है। इसमें compiler , compile time में decide करके सबसे appropriate method को select करता है।

Java Compile Time Polymorphism Example

File : Main.java

CopyFullscreenClose FullscreenRun
class Calculate {  
  static int sum(int a,int b) {
  	return a+b;
  }  
  
  // define another method with different no of parameters.
  static int sum(int a,int b,int c) {
  	return a+b+c;
  }  
}  

public class Main {  
  public static void main(String[] args) {  
    System.out.println(Calculate.sum(23,2));  
    System.out.println(Calculate.sum(3,4,34));  
  }
}
Output
javac Main.java
java Main
25
41

Java Run Time Polymorphism

इस प्रकार के Polymorphism को Method Overriding के द्वारा achieve किया जाता है। इसमें object method को base class के अलावा child class में भी define कर दिया जाता है ,जैसा कि आप पिछले topic में पढ़ा चुके हैं।

Runtime polymorphism को Dynamic Method Dispatch भी कहते हैं , जहाँ overridden method को runtime पर resolve किया जाता है।

Java Run Time Polymorphism Example

File : Dog.java

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

class Horse extends Animal {
  void eat() {
    System.out.println("Horse eats grass.");
  } 
}

class Dog extends Animal {
  void eat() {
    System.out.println("Dog eats fisha and vegetables.");
  } 
}

// main class.
public class Main {
  public static void main(String args[]){  
    Dog d = new Dog();  // create Dog object.
    Horse h = new Horse(); // create Horse Object.
    d.eat();
    h.eat();
  }
}
Output
javac Dog.java
java Dog
Dog eats fisha and vegetables.
Horse eats grass.

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