Wednesday, June 3, 2020

4.3 OOPS basics - Inheritance and Polymorphism

1. What is Polymorphism?
Polymorphism is the ability of an object to take on many forms. In a same class or classes inheriting other class having same method name with different behavior (Overriding) and same method with different in number,type and order arguments(Over loading) is know as Polymorphism.

2. What is runtime polymorphism or dynamic method dispatch?


3. Difference between overloading and method overriding?


4. How to prevent override method in Java?
There are three different ways to prevent overriding of method in Java. The following three approach does that
  • Private method cannot be overridden, because it is not visible to the other class.
  • Static method can also not be overridden, because it relates with class rather than objects. So it hides the method to the child class.
  • Final method cannot be overridden, because it doesn't allows redefinition of the method.

5. What is Inheritance and its types?
Inheritance is the process of using extends keyword,  the attributes and behaviors of one class used in  the other class.

6. What is multiple inheritance and does java support?
In multiple inheritance, child class inherits the properties of two parents classes. Multiple parent classes may contains the same method signature causes the confusion in the child class which method to inherit during runtime, called as diamond problem. There is no virtual keyword in java to avoid this problem. Due to this problem, java doesn't allow inheritance with classes but it allows using interface.

7. What is the difference between super() and this()?
super() is constructor of an immediate parent class. this() is a current class constructor.
Example:
class A{
A(){
System.out.println("Class A no argument constructor called");
}
}
class B extends A{
B(){
System.out.println("Class B no argument constructor called");
}
B(String s){
this();
System.out.println("Class B argument constructor called");
}
}
public class Constructor{
public static void main(String[] args) {
new B("Learn");
}

}

Output & Explanation:
Class A no argument constructor called
Class B no argument constructor called

Class B argument constructor called



8. What is the super class of all java classes?

Object class is a super class of all java classes which is available in java.lang.object. All user defined class extends from object class and it follows simple inheritance, because it collects the behaviors of objects to the implemented class.

9. How can you create an immutable class in java?
  • Define class as final public (extends are not allowed)
  • Define the properties inside class also private and final
  • Assign the values with the help of constructor
  • Declare only getter method() (setter method not allowed)
Example:
final public class Immutable{
private final int a;
public Immutable(int a){
this.a=a;
}
public int getA(){
return this.a;
}
}
10.

No comments:

Post a Comment