-->

Java OOPS Interview Question Part 2

Posted by Admin on
Inheritance (Object-Oriented Programming)
Inheritance is a mechanism in which one object acquires all the properties and behaviour of parent object.The idea behind inheritance is that when you create a new class you reuse the code of the parents class on basis of which derived class has been created.


Why do we use use Inheritance?
•For Code Reusability











As you can see in the above figure is that rectangle is derived which has been created on the basis of shape class which mean rectangle class can reuse the code of the shape class.

Types of Inheritance:




Note:Multiple inheritance is not supported in java in case of class.

When a class extends two classes i.e. known as multiple inheritance.For Example:


Q:-Why multiple inheritance is not supported in java?

1) First reason is ambiguity around Diamond problem, consider a class A has draw() method and then B and C derived from A and has there own draw() implementation and now class D derive from B and C using multiple inheritance and if we refer just draw() compiler will not be able to decide which draw() it should invoke. This is also called Diamond problem because structure on this inheritance scenario is similar to 4 edge diamond, see below
       
           A draw()
           /      \
          /        \ 
        /           \
   draw()     C draw()
          \          /
           \       /
            \     /
            D draw()
2) Second and more convincing reason to me is that multiple inheritances does complicate the design and creates problem during casting, constructor chaining etc and given that there are not many scenario on which you need multiple inheritance its wise decision to omit it for the sake of simplicity. Also java avoids this ambiguity by supporting single inheritance with interfaces. Since interface only have method declaration and doesn't provide any implementation there will only be just one implementation of specific method hence there would not be any ambiguity.

Which class is the superclass for every class.
Object class.

Method Overriding in Java
If a subclass provides a specific implementation of a method that is already provided by its super class, it is known as Method Overriding.

Why do we use Method Overriding ?
Method Overriding is used for Runtime Polymorphism.

//Example of method overriding
 
  class Vehicle{
  void run(){System.out.println("Vehicle is running");}
  }
  class Bike extends Vehicle{
  void run(){System.out.println("Bike is running safely");}
 
  public static void main(String args[]){
  Bike obj = new Bike();
  obj.run();
  }
}


Why we cannot override static method?
because static method is bound with class whereas instance method is bound with object. Static belongs to class area and instance belongs to heap area.

Explain all the access specifiers in Java.
There are 4 types of access modifiers:
1.private
2.default
3.protected
4.public

Private The private access modifier is accessible only within class.
DefaultIf you don't use any modifier, it is treated as default modifier bydefault. The default modifier is accessible only within package.
ProtectedThe protected access modifier is accessible within package and outside the package by only through inheritance. The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.
Public The public access modifier is accessible everywhere. It has the widest scope among all other modiers.

Explain the use of super keyword in Java.
super is a reference variable that is used to refer immediate parent class object.
Uses of super Keyword:
1.super is used to refer immediate parent class instance variable.
2.super() is used to invoke immediate parent class constructor.
3.super is used to invoke immediate parent class method.

//example of super keyword
class A{
  int a=50;
}
class B extends A{
  int a=100;
  
  void display(){
   System.out.println(super.a);//will print va;ue of a in class A(means 50 in this case)
  }
  public static void main(String args[]){
   B b=new B();
   b.display();
 
}
}


When is the final Keyword used in Java ?
The final keyword in java is used to restrict the user. The final keyword can be used in many context. Final can be:
1.variable
2.method
3.class
final variable : If you make any variable as final, you cannot change the value of final variable(It will be constant).
final method : If you make any method as final, you cannot override it.
final class : If you make any class as final, you cannot extend it.

Is final method inherited?
Yes, final method is inherited but you cannot override it.

Can we declare a constructor as final?
No, because constructor is never inherited.

Can you have virtual functions in Java?
In Java, all non-static methods are by default "virtual functions." Only methods marked with the keyword final, which cannot be overridden, along with private methods, which are not inherited, are non-virtual.
See the following example. In the following example we are overridin  normal java method which mean every method in java is virtual method:-

class Bike{
    void run(){
System.out.println("running ");}
 }
 
 class Honda extends Bike{
 void run(){System.out.println("running safely..");}
 
 public static void main(String args[]){
  Honda obj = new Honda();
  obj.run();
 }
}

What are the main difference between Interface and Abstract Class?

                        Interface                                                                       Abstract Class                               
Java interface are implicitly abstract and cannot have implementationsJava abstract class can have instance methods that implements a default behavior.
Variables declared in a Java interface is by default finalAbstract class may contain non-final variables
Members of a Java interface are public by defaultJava abstract class members can be private, protected, etc..
Interface provides 100% abstractionAbstract class does not provide 100% abstraction.

Can there be any abstract method without abstract class?
No, if there is any abstract method in a class, that class must be abstract.

Can you use abstract and final both with a method?
No, because abstract method needs to be overridden whereas you can't override final method.

Is it possible to instantiate the abstract class?
No, abstract class can never be instantiated.

Can you declare an interface method static?
No, because methods of an interface is abstract bydefault, and static and abstract keywords can't be used together.

Can an Interface be final?
No, because its implementation is provided by another class.

(Very Important )Runtime Polymorphism(Dynamic Dispatch method)
Runtime Polymorphism is a mechanism by which a call to an overridden function is resolved at runtime rather compile time.See the below example :

class Bike{
   void run(){System.out.println("running");}
 }
 class Splender extends Bike{
   void run(){System.out.println("running safely with 60km");}
 
   public static void main(String args[]){
     Bike b = new Bike();
     Splender s=new Splender();
     b=s;//assigning the derived class object to base class 
     b.run();// calling the derived class method using base class object
   }
 }

Ouput:
running safely with 60km

Please comment if you find any mistakes.


No comments:

Post a Comment