Java OOP Interview Questions – Part 02

Hello guys,

I’m back with another article in our Java OOP Interview Questions article series. Today I’ll be discussing another 10 questions regarding the deadly diamond of death, UML relationship types, sorting, serialization, static blocks and many more. Without further ado, let’s get into the fun stuff.


11. Why doesn’t Java support multiple inheritance?

As you may already know, Java does not support a class to inherit from multiple superclasses. But languages like C++ and Python do support multiple inheritance.

The reason behind Java’s restriction is to avoid ambiguity or as some people like to say to avoid the deadly diamond of death. Let me explain the deadly diamond concept using this image.

Deadly Diamond of Death

Think of the following idea with the assumption that Java supports multiple inheritance.

Here we have classes B and C that inherits from class A and then we have class D inherits both B and C. If A has a method called run(), and both B and C have overridden it, what method is D going to inherit from? Class B’s run() method or class C’s method?

This is the reason why Java does not provide the ability to inherit from multiple classes.

12. Explain UML Relationships: Directed Association, Aggregation, Composition, Generalization

  1. Directed Association

Directed Association helps to depict the elements that are associated. These are weak relationships

A Car uses A Garage

  1. Aggregation

This is also a type of association. The difference here is that the associated part is crucial for the other element. But still, this also is considered as a weak relationship

A Car needs Tires. But a Tire doesn’t need a Car

  1. Composition

Composition is a strong relationship.

A House is composed of Stones

These two are tightly bonded together because if we remove stones, there won’t be a structure called a house as well.

  1. Generalization

These are the relationships that depict inheritance.

13. What is the difference between Comparable and Comparator in Java?

These are two interfaces that Java provides to sort objects.

When we are using the Comparable interface (from java.lang package), we can go on the following process.

We need to implement Comparable interface for the Entity class. Then we need to implement the compareTo() method in the way we want to get the objects sorted. After that, we just need to call Collections.sort() and pass object list we want to get sorted.

The process that we need to do when using the Comparator (from java.util package) interface is a bit different.

Here we need to create a separate class that implements the Comparator interface. Then inside that class, we need to implement the compare() method to sort out data. And then when we are calling Collections.sort(), we need to pass the comparator class as the second parameter and Java will handle the rest.

The main difference is that when using Comparable interface, we can only create a single sorting sequence. But with Comparator interface, we can sort as much sorting sequences as we need.

In addition, we have to modify the entity class if we are going to implement the Comparable interface.

14. What is Serialization in Java?

This guy can’t read your data directly now 😪

Serialization in Java is the process of writing data of an object to a byte stream.

We can use the Serializable interface in Java to achieve this feat. Serializable is a marker interface which means that it doesn’t have any methods or variables. It is only used to mark the entity classes so that the compiler knows that he needs to get ready to serialize that particular entity class.

Here is a simple code snippet on how to serialize an object in Java.

Student Class

package serialization;

import java.io.Serializable;

public class Student implements Serializable {

    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

Main Class

package serialization;

import java.io.*;

public class Main {

    public static void main(String[] args) throws IOException {

        Student student = new Student("Thisura", 22);

        FileOutputStream fileOutputStream = new FileOutputStream("thisura.txt");
        ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream);
        outputStream.writeObject(student);
        outputStream.flush();
        outputStream.close();
    }
}

When we run the code, a text file called thisura.txt gets created in directory and the object gets stored in the file as a byte stream.

We can deserialize using the ObjectInputStream  and FileInputStream.

15. When should we use static methods and variables in Java?

We should declare a variable as static when we are sharing data

We should declare methods as static when we are using them as utility methods

16. Does a constructor return a value?

Yes, it returns the current class instance

17. What are the restrictions we have to face when using static methods?

Static methods can’t use non-static variables or methods

this and super keywords can’t be used in static methods

There is no need to create an object of the class to invoke a static method

static methods can’t be overridden in subclasses

18. Why is the main method in Java static?

The main method in Java needs to be declared as a static method so that the compiler does not have to create an object before calling it.

Since it is from the main method that the program start, the main method should always be static so that the compiler can call it right away.

19. When do we use static blocks?

We use static blocks to initialize static variables.

This block of code gets executed once the class is loaded into the memory. A class can have multiple static blocks. Here is a code snippet to explain it quickly.

    private String name;
    private int age;
    static String school;

    static {
        school = "Westminster";
    }

Before Java 7, it was possible to even execute a program without a main method. That is by using static blocks. Since the static block is executed once the class is loaded to the memory, we can write whatever we want inside the static method and run.

If we try to run the main method without the static keyword, the following error occurs.

Error: Main method is not static in class abstraction.Main, please define the main method as:
   public static void main(String[] args)

20. When should we use this and super keywords in Java?

this keyword is used to access a certain method or variable of the current object. This is commonly used to get rid of the confusion between class variables and parameters inside constructors.

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

We can just create the constructor like the below code and could get rid of this keyword.

    public Student(String myName, int myAge) {
        name = myName;
        age = myAge;
    }

We use super keyword when we want to access variables or methods of the superclass. In addition, we can call superclass constructor by writing super().

Another fun fact about these two keywords is that, we can’t call super() and this() in the same constructor since both methods must be the first line of code in the constructor.


That is it for this article. Hope you guys learned something valuable. If you have any doubts, please drop a comment down below, I’ll try to answer it. See you soon 😎

Published by Thisura Thenuka

I am a passionate software engineering student. But cricket is my first love ❤

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: