Interview Questions
Question: - What is Polymorphism?
Answer: - Polymorphism means one name many forms. In other words we can say that, polymorphism allows us to define one interface which is having multiple implementations. It is the capability of methods to behave differently based on the object that is acting upon it. We can achieve Polymorphism using inheritance, method overloading and method overriding.
Polymorphism is categorized in two types:-
- Compile time polymorphism or static binding or early binding that is achieved through Overloading
- Runtime polymorphism or dynamic binding or late binding that is achieved through Overriding.
Question:- What is compile time polymorphism?
Answer:-
Compile time polymorphism: -
In compile time polymorphism the calling function body is decided on compile-time means before execution or at compilation time only, the called function is already having the implementation details.
Question:- What is method overloading?
Answer:- Method or function overloading
- Overloaded methods have the same name but having different parameter lists and can have different return types. It can appear in the same class or in the sub class.
Few example of Method Overloading in JAVA API :- getBytes() , indexOf (), lastIndexOf(), replace(), split(), startsWith(), substring(), toLowerCase(), toUpperCase(), valueOf() e.t.c methods in String class,
MethodOverloadingTestDemo.java
package com.gaurav.methodoverloading;
public class MethodOverloadingTestDemo {
public String displayParameterValues() {
System.out.println("********************************************************************************");
System.out
.println("Inside overloaded displayParameterValues() method having No Parameters");
return "No Parameters passed";
}
public int displayParameterValues(int number) {
System.out.println("********************************************************************************");
System.out
.println("Inside overloaded displayParameterValues() method having int as a Parameters");
return number;
}
public double displayParameterValues(double num) {
System.out.println("********************************************************************************");
System.out
.println("Inside overloaded displayParameterValues() method having double as a Parameters");
return num;
}
}
MethodOverloadingTestDemoCaller.java
package com.gaurav.methodoverloading;
public class MethodOverloadingTestDemoCaller extendsMethodOverloadingTestDemo {
public String displayParameterValues(String name) {
System.out.println("********************************************************************************");
System.out
.println("Inside overloaded displayParameterValues() method in subclass having String as a Parameters ");
return name;
}
public static void main(String args[]) {
MethodOverloadingTestDemo mtd = new MethodOverloadingTestDemo();
System.out.println("Fucntion returning the parameter value is : "+mtd.displayParameterValues());
System.out.println("Fucntion returning the parameter value is : "+mtd.displayParameterValues(10));
System.out.println("Fucntion returning the parameter value is : "+mtd.displayParameterValues(99.75));
MethodOverloadingTestDemoCaller mtdc = newMethodOverloadingTestDemoCaller();
System.out.println("Fucntion returning the parameter value is : "+mtdc.displayParameterValues("KUMAR GAURAV"));
}
}
Result:-
********************************************************************************
Inside overloaded displayParameterValues() method having No Parameters
Fucntion returning the parameter value is : No Parameters passed
********************************************************************************
Inside overloaded displayParameterValues() method having int as a Parameters
Fucntion returning the parameter value is : 10
********************************************************************************
Inside overloaded displayParameterValues() method having double as a Parameters
Fucntion returning the parameter value is : 99.75
********************************************************************************
Inside overloaded displayParameterValues() method in subclass having String as a Parameters
Fucntion returning the parameter value is : KUMAR GAURAV
Question: - What is Constructor Overloading?
Answer:-
Constructor Overloading:-
- It is a technique in Java in which a class can have any number of constructors having different parameter lists.
- Java compiler is capable to differentiate these constructors by identifying the number of parameters in the list and their type.
In Java API, String class is having multiple overloaded constructors. Similarly in util package, ArrayList, HashMap, HashSet e.t.c classes is also having multiple overloaded constructors.
Some signatures of the overloaded constructor in String class are:-
- String()
- String(byte[] bytes)
- String(StringBuffer buffer)
- String(StringBuilder builder)
Similarly, few overloaded constructors of HashMap class are:-
- HashMap()
- HashMap(int initialCapacity)
- HashMap(int initialCapacity, float loadFactor)
Example of constructor overloading
package com.gaurav.overloading;
public class StudentComparison {
public StudentComparison() {
System.out.println("No parameter passed, hence No comparison made.");
}
public StudentComparison(int firstEmpage, intsecondEmpAge) {
Integer int1 = Integer.valueOf(firstEmpage);
Integer int2 = Integer.valueOf(secondEmpAge);
if (int1.compareTo(int2) > 0)
System.out.println("First student is elder than second.");
if (int1.compareTo(int2) < 0)
System.out.println("First student is younger than second.");
if (int1.compareTo(int2) == 0)
System.out.println("Both student is having same age.");
}
public StudentComparison(String firstEmpName, String secondEmpName) {
int result = firstEmpName.compareTo(secondEmpName);
if (result > 0)
System.out
.println("Sorting made on the basis of second student name.");
if (result < 0)
System.out
.println("Sorting made on the basis of first student name.");
if (result == 0)
System.out.println("No sorting made.");
}
@SuppressWarnings("unused")
public static void main(String args[]) {
StudentComparison sc1 = new StudentComparison();
StudentComparison sc2 = new StudentComparison(30, 40);
StudentComparison sc3 = new StudentComparison("GAURAV", "AADITYA");
}
}
Result:-
No parameter passed, hence No comparison made.
First student is younger than second.
Sorting made on the basis of second student name.
First student is younger than second.
Sorting made on the basis of second student name.
Question: - What is Runtime polymorphism?
Answer:-
Runtime polymorphism: -
- In Runtime polymorphism the calling function body is decided during execution time means during compilation which implementation will get executed for the method is unknown. It is defined only at Runtime. Below Example will verify the statement.
- We can achieve dynamic polymorphism or runtime polymorphism using overriding.
- Dynamic binding is also known as dynamic method dispatch because which overridden method needs to be dispatched for execution is known at runtime.
Basic things about overriding:-
- There must be method overriding not overloading
- subclass object must be assigned to super class object
- constructors can't be overridden
- final methods can't be overridden
- static methods can't be overridden
- abstract methods must be overridden.
Dynamic Polymorphism Example:-
package com.gaurav.overloading;
class Car
{
public voidgetMileage()
{
System.out.println("All petrol Cars is having less mileage but having luxurious facility");
}
}
class HyundaiElantra extends Car
{
public voidgetMileage()
{
System.out.println("Hyundai Elantra official mileage is 13.1");
}
}
class MarutiKizashi extends Car
{
public voidgetMileage()
{
System.out.println("Maruti Kizashi official mileage is 7.2");
}
}
class BugattiVeyron extends Car
{
public voidgetMileage()
{
System.out.println("Bugatti Veyron official mileage is 3.3");
}
}
public class DynamicPolymorphismTestDemo
{
public static voidmain(String args[])
{
Car car = newCar();
car.getMileage(); // It invokes the parent class getMileage() method.
HyundaiElantra hyundaiElantra = new HyundaiElantra();
car = hyundaiElantra;
car.getMileage(); // It invokes the HyundaiElantra class getMileage() method.
MarutiKizashi marutiKizashi = new MarutiKizashi();
car = marutiKizashi;
car.getMileage(); // It invokes the MarutiKizashi class getMileage() method.
BugattiVeyron bugattiVeyron = newBugattiVeyron();
car = bugattiVeyron;
car.getMileage(); // It invokes the BugattiVeyron class getMileage() method.
}
}
/**
* In the above demo example, we can find that subclass HyundaiElantra object is assigned to super class *Car object. As per the rule, We know if a subclass object is assigned to a superclass object, then *superclass object can call subclass overridden methods. As per this rule we have done like below
* car = hyundaiElantra;
* Now superclass object car can call the getMileage() method of HyundaiElantra class.Similarly it can call *others child class methods, if we assign child class references to superclass object.
*/
Result:-
All petrol Cars is having less mileage but having luxurious facility
Hyundai Elantra official mileage is 13.1
Maruti Kizashi official mileage is 7.2
Bugatti Veyron official mileage is 3.3
Hyundai Elantra official mileage is 13.1
Maruti Kizashi official mileage is 7.2
Bugatti Veyron official mileage is 3.3
Achieving dynamic polymorphism using interfaces
package com.gaurav.overloading;
interface LuxuryCar
{
publicvoid getMileage();
}
class BentleyContinental implements LuxuryCar
{
publicvoidgetMileage()
{
System.out.println("Bentley Continental official mileage is 5.3");
}
}
class FerrariCalifornia implements LuxuryCar
{
publicvoidgetMileage()
{
System.out.println("Ferrari California official mileage is 6.0");
}
}
class PorscheBoxster implements LuxuryCar
{
publicvoidgetMileage()
{
System.out.println("Porsche Boxster official mileage is 4.8");
}
}
public class DynamicPolyUsingInterfaceDemo
{
publicstatic void main(String args[])
{
LuxuryCar luxuryCar; //It's just a interface reference variable not an object.
BentleyContinental bentleyContinental = newBentleyContinental();
luxuryCar = bentleyContinental;
luxuryCar.getMileage(); // It invokes the BentleyContinental class getMileage() method.
FerrariCalifornia ferrariCalifornia = newFerrariCalifornia();
luxuryCar = ferrariCalifornia;
luxuryCar.getMileage(); // It invokes the FerrariCalifornia class getMileage() method.
PorscheBoxster porscheBoxster = newPorscheBoxster();
luxuryCar = porscheBoxster;
luxuryCar.getMileage(); // It invokes the PorscheBoxster class getMileage() method.
}
}
/**
* Subclass BentleyContinental object is assigned to the reference variable LuxuryCar. Here, super class is * an interface and getMileage() is an abstract method. When a subclass object is assigned to a super class * reference variable, the reference variable calls subclass overridden method. Now,
* luxuryCar can call other subclass methods and it depends upon the assignment to the interface reference * variable.
* Each time we are replacing the addresses of subclass objects with, bentleyContinental, ferrariCalifornia *and porscheBoxster objects in the reference variable luxuryCar dynamically at runtime. Every time when
* luxuryCar.getMileage() method is called, it prints different outputs depends on the assigned reference *objects. Here in the above both examples we are achieving polymorphism at runtime means dynamically, *this is known as dynamic polymorphism or late binding or runtime polymorphism. Here, dynamic *polymorphism is achieved through
* interfaces.
*/
Result:-
Bentley Continental official mileage is 5.3
Ferrari California official mileage is 6.0
Porsche Boxster official mileage is 4.8
No comments:
Post a Comment