April 06, 2016

#Java: Part 2-Core Java Interview Questions and Answers (Polymorphism, Overloading and Overriding)

>> Check the Part 1-Core Java Interview Questions and Answers

What is Inheritance?
It is the mechanism by which an object acquires some/all properties of another object. Inheritance provides the idea of reusability of code and each sub class defines only those features that are unique to it.

The existing (or original) class is called the base class or super class or parent class. The new class which inherits from the base class is called the derived class or sub class or child class. Inheritance implements the “Is-A” or “Kind Of/ Has-A” relationship.

Advantages of Inheritance:
# Inheritance is a mechanism of defining a new class based on an existing class, which enables reuse of code. That means code in base class need not be rewritten in the derived class.
# It also provides scope for refinement of the existing class.

Types of Inheritance
Multilevel Inheritance refers to a mechanism in OO technology where one can inherit from a derived class, thereby making this derived class the base class for the new class.
Multiple Inheritance refers to the concept of one class inheriting from more than one base class. The problem with “multiple inheritance” is that the derived class will have to manage the dependency on two base classes.

Multi-level inheritance is allowed in Java but multiple inheritance is not.

What is Polymorphism?
Polymorphism is the capability of a method to do different things based on the object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementations.

Its the ability of a single variable of a given type to be used to reference objects of different types, and automatically call the method that is specific to the type of object the variable references.

Types of Polymorphism in Java:
1) Method Overloading
2) Method Overriding

Method Overloading:
  • It is also known as compile time polymorphism or Static polymorphism.
  • In this we can define two or more methods of same name in a class, provided that there argument list or parameters are different.
  • Overloaded methods may have different return types; the return type alone is insufficient to distinguish two versions of a method.
  • When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call.
  • An overloaded method can throw different exceptions.
  • It can have different access modifiers.
  • Constructors can be overloaded
Method Overriding :
  • It is also known as run time polymorphism or Dynamic polymorphism.
  • Its the ability of a single variable of a given type to be used to reference objects of different types, and automatically call the method that is specific to the type of object the variable references. 
  • Child class has the same method as of base class. In such cases child class overrides the parent class method without even touching the source code of the base class. 
  • The argument list of overriding method must be same as that of the method in parent class. The data types of the arguments and their sequence should be maintained as it is in the overriding method.
  • Overriding method can have different return type.
  • Overriding method must not have more restrictive access modifier. For e.g. if the Access Modifier of base class method is public then the overriding method (child class method ) cannot have private, protected and default Access modifier as all of the three are more restrictive than public.
  • Abstract methods must be overridden
  • private, static and final methods cannot be overridden as they are local to the class. However static methods can be re-declared in the sub class, in this case the sub-class method would act differently and will have nothing to do with the same static method of parent class.
  • Overriding method (method of child class) can throw any unchecked exceptions, regardless of whether the overridden method(method of parent class) throws any exception or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method.
  • non static methods cannot be overridden as static and vice-versa.
  • Constructors cannot be overridden.
Can you override static method in Java?
Static methods belong to the class and not the objects. Since they belong to the class and hence doesn't fit properly for the polymorphic behavior.

Static methods are resolved at compile time rather than runtime. Though you can declare and define static method of same name and signature in the child class, this will hide the static method from parent class, that's why it is also known as method hiding in Java.

Suppose you have declared a Father class, which is extended by Son. Both the classes have method 'static void sayHello()'.

Father f=new Son();
f.sayHello();


This will always call sayHello() method from Father class. (if sayHello() was not declared static then, sayHello() from Son will be called)

Can we change the argument list of an overriding method?
No, you cannot.

Can we override a private method in Java?
No, you cannot. Since the private method is only accessible and visible inside the class they are declared, it's not possible to override them in subclasses. Though, you can override them inside the inner class as they are accessible there

Can we have a non-abstract method inside interface?
From Java 8 onward you can have a non-abstract method inside interface, prior to that it was not allowed as all method was implicitly public abstract. From JDK 8, you can add static and default method inside an interface.

Can we overload or override the main method in Java?
No, since main() is a static method, you can only overload it, you cannot override it because the static method is resolved at compile time without needing object information hence we cannot override the main method in Java.

What is Covariant return?
Before 1.5, when you override a super-class method, the name, argument types and return type of the overriding method has to be exactly same as that of super-class method. Overriding method is said to be invariant with respect to argument types and return type.

But now, since Java 5, it is possible to override method by changing the return type if subclass overrides any method whose return type is Non-Primitive but it changes its return type to subclass type.

The covariant return type in java, allows narrowing down return type of the overridden method. This feature will help to avoid down casting on the client side.

What will be the output of this programme?
public static void printIt(Integer i)
{
    System.out.println("Printing Integer value :"+i);
}
public static void printIt(int i)
{
    System.out.println("Printing int value :"+i);
}
public static void main(String[] args) {
    printIt(7);
}

It will print :
Printing int value :7

What will happen when you throw exception while overriding method?
public class Parent {
    public void printIt(int i)
    {
        System.out.println("Printing int value in Parent :"+i);
    }
}

public class Child extends Parent {
    @Override
    public void printIt(int i) throws IOException
    {
        System.out.println("Printing int value in Child :"+i);
    }
}


You will get an compile time error : 'Exception IOException is not compatible with throws clause in Parent.printIt(int)'.

How compiler handles the exceptions in overriding?
  • The overriding methods can throw any runtime Exception, here in the case of runtime exception overriding method (subclass method) should not worry about exception being thrown by super-class method.
  • If super-class method does not throw any exception then while overriding, the subclass method can not throw any new checked exception but it can throw any runtime exception
  • Different exceptions in java follow some hierarchy tree(inheritance). In this case, if super-class method throws any checked exception, then while overriding the method in subclass we can not throw any new checked exception or any checked exception which are higher in hierarchy than the exception thrown in super-class method

If the method in parent class throws RuntimeException, can the overriding method throws IOException?
No

If an overridden is throwing some exception, is it mandatory to mention throws in overriding method?
No, its not mandatory.

ALSO CHECKCore Java Interview Questions And Answers

-K Himaanshu Shuklaa..

No comments:

Post a Comment