In Java, polymorphism is a feature of object-oriented programming that allows objects to take on multiple forms or types. Polymorphism is achieved through two mechanisms: method overloading and method overriding. Here are some basics of polymorphism in Java:
1. Method overloading: Method overloading is a technique that allows a class to have multiple methods with the same name but different parameters. The method that is called depends on the number and types of the arguments passed. For example:
public class Calculator { public int add(int x, int y) { return x + y; } public double add(double x, double y) { return x + y; } } Calculator calc = new Calculator(); int result1 = calc.add(2, 3); // calls the int version of add() double result2 = calc.add(2.5, 3.5); // calls the double version of add()
Here, the `add` method is overloaded with two versions: one that takes two integers and one that takes two doubles.
2. Method overriding: Method overriding is a technique that allows a subclass to provide its own implementation of a method that is already defined in the superclass. The subclass method must have the same name, return type, and parameters as the superclass method. For example:
public class Person { public void sayHello() { System.out.println("Hello!"); } } public class Student extends Person { public void sayHello() { System.out.println("Hi there!"); } } Person person = new Person(); person.sayHello(); // prints "Hello!" Student student = new Student(); student.sayHello(); // prints "Hi there!"
Here, the `Student` class overrides the `sayHello` method of the `Person` class.
3. Polymorphic reference: A polymorphic reference is a variable that can refer to objects of different types. This is possible because all objects in Java are descendants of the `Object` class. For example:
Person person1 = new Person(); Person person2 = new Student();
Here, `person1` is a reference to an object of the `Person` class, and `person2` is a reference to an object of the `Student` class. Because `Student` is a subclass of `Person`, `person2` can be referred to as a `Person` object.
Polymorphism is a powerful feature of object-oriented programming in Java, and it allows for code reuse and flexibility. By using polymorphism, you can write code that is more generic and can work with objects of different types without knowing their specific types at compile time.