Java Interview QuestionsNo Comments

Advanced Object Oriented Concepts

1. What is Polymorphism?

Polymorphism is defined as “Same Code” giving “Different Behavior”. Let’s look at an example.
Let’s define an Animal class with a method shout.

public class Animal {
    public String shout() {
        return "Don't Know!";
    }
}

Let’s create two new sub classes of Animal overriding the existing shout method in Animal.

class Cat extends Animal {
    public String shout() {
        return "Meow Meow";
    }
}

class Dog extends Animal {
    public String shout() {
        return "BOW BOW";
    }

    public void run() {}
}

Look at the code below. An instance of Animal class is created. shout method is called

Animal animal1 = new Animal();
System.out.println(animal1.shout());  //Don't Know!

Look at the code below. An instance of Dog class is created and store in a reference variable of type Animal.

Animal animal2 = new Dog();

//Reference variable type => Animal	
//Object referred to =>	Dog	
//Dog's bark method is called.	
System.out.println(animal2.shout());  //BOW BOW

When shout method is called on animal2, it invokes the shout method in Dog class (type of the object pointed to by reference variable animal2).
Even though dog has a method run, it cannot be invoked using super class reference variable.

//animal2.run();  //COMPILE ERROR

2. What is the use of instanceof Operator in Java?

instanceof operator checks if an object is of a particular type. Let us consider the following class and interface declarations:

class SuperClass {}

class SubClass extends SuperClass {}

interface Interface {}

class SuperClassImplementingInteface implements Interface {}

class SubClass2 extends SuperClassImplementingInteface {}

class SomeOtherClass {}

Let’s consider the code below. We create a few instances of the classes declared above.

SubClass subClass = new SubClass();
Object subClassObj = new SubClass();

SubClass2 subClass2 = new SubClass2();
SomeOtherClass someOtherClass = new SomeOtherClass();

Let’s now run instanceof operator on the different instances created earlier.

System.out.println(subClass instanceof SubClass);  //true	
System.out.println(subClass instanceof SuperClass);  //true	
System.out.println(subClassObj instanceof SuperClass);  //true	

System.out.println(subClass2 instanceof SuperClassImplementingInteface);  //true

instanceof can be used with interfaces as well. Since Super Class implements the interface, below code prints true.

System.out.println(subClass2 instanceof Interface);  //true

If the type compared is unrelated to the object, a compilation error occurs.

//System.out.println(subClass instanceof SomeOtherClass);  //Compiler Error

Object referred by subClassObj(SubClass)- NOT of type SomeOtherClass

System.out.println(subClassObj instanceof SomeOtherClass);  //false

3. What is Coupling?

Coupling is a measure of how much a class is dependent on other classes. There should minimal dependencies between classes. So, we should always aim for low coupling between classes.


4. What is Cohesion?

Cohesion is a measure of how related the responsibilities of a class are. A class must be highly cohesive i.e. its responsibilities (methods) should be highly related to one another.


5. What is Encapsulation?

Encapsulation is “hiding the implementation of a Class behind a well defined interface”. Encapsulation helps us to change implementation of a class without breaking other code.


6. What is an Inner Class?

Inner Classes are classes which are declared inside other classes. Consider the following example:

class OuterClass {

    public class InnerClass {}

    public static class StaticNestedClass {}

}

7. What is a Static Inner Class?

A class declared directly inside another class and declared as static. In the example above, class name StaticNestedClass is a static inner class.


8. How to create an inner class inside a method?

Yes. An inner class can be declared directly inside a method. In the example below, class name MethodLocalInnerClass is a method inner class.

class OuterClass {

    public void exampleMethod() {
        class MethodLocalInnerClass {};
    }

}

9. What is an Anonymous Class?

Anonymous Class does not have a name. Below examples shows various ways to create Anonymous classes.

class Animal {
    void bark() {
        System.out.println("Animal Bark");
    }
};
public class AnonymousClass {
    private static String[] reverseSort(String[] array) {
        Comparator < String > reverseComparator = new Comparator < String > () {
            /* Anonymous Class */
            @Override
            public int compare(String string1, String string2) {
                return string2.compareTo(string1);
            }
        };
        Arrays.sort(array, reverseComparator);
        return array;
    }
    public static void main(String[] args) {
        String[] array = {
            "Apple",
            "Cat",
            "Boy"
        };
        System.out.println(Arrays.toString(reverseSort(array)));  //[Cat, Boy, Apple] 
        /* Second Anonymous Class - SubClass of Animal*/
        Animal animal = new Animal() {
            void bark() {
                System.out.println("Subclass bark");
            }
        };
        animal.bark();  //Subclass bark 
    }
}