Java OOPS Interview Questions

Interview Questions on OOPS concepts cover a varied range of topics. The picture show an overview of all the topics we would cover in this article on interview questions.

  1. What is the super class of every class in Java?
  2. Can super class reference variable can hold an object of sub class?
  3. Is Multiple Inheritance allowed in Java?
  4. What is Polymorphism?
  5. What is the use of instanceof Operator in Java?
  6. What is an Abstract Class?
  7. How do you define an abstract method?
  8. What is Coupling?
  9. What is Cohesion?
  10. What is Encapsulation?
  11. What is Method Overloading?
  12. What is Method Overriding?
  13. What is an Inner Class?
  14. What is a Static Inner Class?
  15. Can you create an inner class inside a method?

What is the super class of every class in Java?

Every class in java is a sub class of the class Object. When we create a class we inherit all the methods and properties of Object class. Let’s look at a simple example:In the example below - toString, hashCode and clone methods for String class are inherited from Object class.

String str = "Testing";
System.out.println(str.toString());
System.out.println(str.hashCode());
System.out.println(str.clone());

if(str instanceof Object){
    System.out.println("I extend Object");//Will be printed
}

Can super class reference variable can hold an object of sub class?

Yes. Look at the example below:

Actor reference variables actor1, actor2 hold the reference of objects of sub classes of Animal, Comedian and Hero.

Since object is super class of all classes, an Object reference variable can also hold an instance of any class.

//Object is super class of all java classes
Object object = new Hero(); 

public class Actor {
    public void act(){
        System.out.println("Act");
    };
}

//IS-A relationship. Hero is-a Actor
public class Hero extends Actor {
    public void fight(){
        System.out.println("fight");
    };
}

//IS-A relationship. Comedian is-a Actor
public class Comedian extends Actor {
    public void performComedy(){
        System.out.println("Comedy");
    };
}

Actor actor1 = new Comedian();
Actor actor2 = new Hero();

Is Multiple Inheritance allowed in Java?

Multiple Inheritance results in a number of complexities. Java does not support Multiple Inheritance.

class Dog extends Animal, Pet { //COMPILER ERROR
}

However, we can create an Inheritance Chain

class Pet extends Animal {
}

class Dog extends Pet {
}

What is Polymorphism?

Refer to this video(https://www.youtube.com/watch?v=t8PTatUXtpI) for a clear explanation of 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

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

What is an Abstract Class?

An abstract class (Video Link - https://www.youtube.com/watch?v=j3GLUcdlz1w) is a class that cannot be instantiated, but must be inherited from. An abstract class may be fully implemented, but is more usually partially implemented or not implemented at all, thereby encapsulating common functionality for inherited classes.

In code below ”AbstractClassExample ex = new AbstractClassExample();” gives a compilation error because AbstractClassExample is declared with keyword abstract.

public abstract class AbstractClassExample {
    public static void main(String[] args) {
        //An abstract class cannot be instantiated
        //Below line gives compilation error if uncommented
        //AbstractClassExample ex = new AbstractClassExample();
    }
}

How do you define an abstract method?

An Abstract method does not contain body. An abstract method does not have any implementation. The implementation of an abstract method should be provided in an over-riding method in a sub class.

    //Abstract Class can contain 0 or more abstract methods
    //Abstract method does not have a body
    abstract void abstractMethod1();
    abstract void abstractMethod2();

Abstract method can be declared only in Abstract Class. In the example below, abstractMethod() gives a compiler error because NormalClass is not abstract.

class NormalClass{
    abstract void abstractMethod();//COMPILER ERROR
}

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.

Coupling Example Problem

Consider the example below:

class ShoppingCartEntry {
    public float price;
    public int quantity;
}

class ShoppingCart {
    public ShoppingCartEntry[] items;
}

class Order {
    private ShoppingCart cart;
    private float salesTax;

    public Order(ShoppingCart cart, float salesTax) {
        this.cart = cart;
        this.salesTax = salesTax;
    }

    // This method know the internal details of ShoppingCartEntry and
    // ShoppingCart classes. If there is any change in any of those
    // classes, this method also needs to change.
    public float orderTotalPrice() {
        float cartTotalPrice = 0;
        for (int i = 0; i < cart.items.length; i++) {
            cartTotalPrice += cart.items[i].price
                    * cart.items[i].quantity;
        }
        cartTotalPrice += cartTotalPrice * salesTax;
        return cartTotalPrice;
    }
}

Method orderTotalPrice in Order class is coupled heavily with ShoppingCartEntry and ShoppingCart classes. It uses different properties (items, price, quantity) from these classes. If any of these properties change, orderTotalPrice will also change. This is not good for Maintenance.

Solution

Consider a better implementation with lesser coupling between classes below: In this implementation, changes in ShoppingCartEntry or CartContents might not affect Order class at all.

class ShoppingCartEntry
{
    float price;
    int quantity;

    public float getTotalPrice()
    {
        return price * quantity;
    }
}

class CartContents
{
    ShoppingCartEntry[] items;

    public float getTotalPrice()
    {
        float totalPrice = 0;
        for (ShoppingCartEntry item:items)
        {
            totalPrice += item.getTotalPrice();
        }
        return totalPrice;
    }
}

class Order
{
    private CartContents cart;
    private float salesTax;

    public Order(CartContents cart, float salesTax)
    {
        this.cart = cart;
        this.salesTax = salesTax;
    }

    public float totalPrice()
    {
        return cart.getTotalPrice() * (1.0f + salesTax);
    }
}

What is Cohesion?

Cohesion (Video Link - https://www.youtube.com/watch?v=BkcQWoF5124) 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.

Example Problem

Example class below is downloading from internet, parsing data and storing data to database. The responsibilities of this class are not really related. This is not cohesive class.

class DownloadAndStore{
    void downloadFromInternet(){
    }
    
    void parseData(){
    }
    
    void storeIntoDatabase(){
    }
    
    void doEverything(){
        downloadFromInternet();
        parseData();
        storeIntoDatabase();
    }
}
Solution

This is a better way of approaching the problem. Different classes have their own responsibilities.

class InternetDownloader {
    public void downloadFromInternet() {
    }
}

class DataParser {
    public void parseData() {
    }
}

class DatabaseStorer {
    public void storeIntoDatabase() {
    }
}

class DownloadAndStore {
    void doEverything() {
        new InternetDownloader().downloadFromInternet();
        new DataParser().parseData();
        new DatabaseStorer().storeIntoDatabase();
    }
}

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.

Approach 1

In this approach we create a public variable score. The main method directly accesses the score variable, updates it.

public class CricketScorer {
    public int score;
}

Let’s use the CricketScorer class.

public static void main(String[] args) {
CricketScorer scorer = new CricketScorer();
scorer.score = scorer.score + 4;
}
Approach 2

In this approach, we make score as private and access value through get and set methods. However, the logic of adding 4 to the score is performed in the main method.

public class CricketScorer {
    private int score;

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }
}

Let’s use the CricketScorer class.

public static void main(String[] args) {
CricketScorer scorer = new CricketScorer();

int score = scorer.getScore();
scorer.setScore(score + 4);
}
Approach 3

In this approach - For better encapsulation, the logic of doing the four operation also is moved to the CricketScorer class.

public class CricketScorer {
    private int score;
    
    public void four() {
        score += 4;
    }

}

Let’s use the CricketScorer class.

public static void main(String[] args) {
CricketScorer scorer = new CricketScorer();
scorer.four();
}
Description

In terms of encapsulation, Approach 3 is the best approach. In Approach 3, the user of scorer class does not even know that there is a variable called score. Implementation of Scorer can change without changing other classes using Scorer.

What is Method Overloading?

A method having the same name as another method (in same class or a sub class) but having different parameters is called an Overloaded Method.

Example 1

doIt method is overloaded in the below example:

class Foo{
    public void doIt(int number){
        
    }
    public void doIt(String string){
        
    }
}
Example 2

Overloading can also be done from a sub class.

class Bar extends Foo{
    public void doIt(float number){
        
    }
}

What is Method Overriding?

Creating a Sub Class Method with same signature as that of a method in SuperClass is called Method Overriding.

Method Overriding Example 1:

Let’s define an Animal class with a method shout.

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

Let’s create a sub class of Animal – Cat - overriding the existing shout method in Animal. bark method in Cat class is overriding the bark method in Animal class.

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

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 {
    }

}

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.

Can you 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 {
        };
    }

}

If you loved these Questions, you will love our PDF Interview Guide with 400+ Questions.
Download it now!.

400+ Interview Questions in 4 Categories:
  1. Java : Core Java, Advanced Java, Generics, Exception Handling, Serialization, Threads, Synchronization, Java New Features
  2. Frameworks : Spring, Spring MVC, Struts, Hibernate
  3. Design : Design, Design Patterns, Code Review
  4. Architecture : Architecture, Performance & Load Testing, Web Services, REST Web Services,Security, Continuous Integration