InterviewSolution
| 1. |
Java Polymorphism |
|
Answer» Polymorphism is a Java feature that allows us to do a single operation in multiple ways. Polymorphism is made up of two Greek words: poly and morphism. The words "poly" and "morphs" denote "many" and "forms," respectively. As a result, polymorphism denotes the presence of several forms. Polymorphism in Java is divided into two types: compile-time polymorphism and runtime polymorphism. Compile-time Polymorphism: Compile-time polymorphism is also known as static polymorphism. In Java, this is achieved by function overloading. Method Overloading: When there are numerous functions with the same name but distinct parameters, this is referred to as overloading. Changes in the number of arguments or the kind of arguments can cause functions to become overloaded. Example - class Sample {// Method with 2 integer parameters static int Multiply(int a, int b) // method overloading { return a * b; } // Method with same name but with 2 double parameters static double Multiply(double a, double b) // method overloading { return a * b; } } class Test { public static void main(String[] args) { // Calling method by passing // input as in arguments System.out.println(Sample.Multiply(1, 4)); System.out.println(Sample.Multiply(5.5, 4.2)); } } Output - 423.1 Explanation: In the above code, the class Sample has two functions with the same name ‘multiply’ but they have different function signatures which implement method overloading. So, we have the same name for a function that returns the multiplication of two integers and a function that returns the multiplication of two doubles. Runtime Polymorphism: Runtime polymorphism, often known as Dynamic Method Dispatch, is a technique for resolving calls to overridden methods at runtime rather than at compile time. A superclass's reference variable is used to call an overridden method in this process. The object referred to by the reference variable is used to determine which method should be called. Example - class Sample{void fun(){ System.out.println("Inside Sample's fun method."); } } class Test extends Sample{ void fun(){ System.out.println("Inside Test's fun method."); } } class Main{ public static void main(String args[]){ Sample s = new Test() s.fun(); } } Output - Inside Test's fun method.Explanation - In the above code, the Test class inherits from the Sample class and both the Test class and the Sample class have a method named ‘fun’ defined. This leads to method overriding. Now in the main class, we create a ‘Sample’ reference variable and allot an instance of the ‘Test’ class to it. Now, we invoke the fun() method. Since, the reference variable stores an object of the ‘Test’ class, the fun() method of the ‘Test’ class gets invoked. |
|