Java Interview Questions and Answers - 2

8. Explain the difference between an Abstract Class and Interface in Java.

Abstract classes can have methods with implementation whereas an interface provides absolute abstraction and can’t have any method implementations.

A class which implements an interface must implement all the methods of the interface while a class which inherits from an abstract class doesn't require implementation of all the methods of its super class.

Subclasses use extends keyword to extend an abstract class whereas subclasses use implements keyword to implement interfaces

A class can implement multiple interfaces but it can extend only one abstract class.

9. Can we declare a class as Abstract without having any abstract method?

Yes, we can have an abstract class without abstract methods as both are independent concepts. Declaring a class abstract means it can’t be instantiated on its own and can only be sub classed. Declaring a method abstract means method will be defined in the subclass.

However, if a class has even one abstract method, it must be declared as abstract otherwise it will give an error.

10. What is an immutable class?

Immutable class is a class which once created; its contents can’t be changed.

Immutable objects are the objects whose state can’t be changed once constructed.

Since the state of the immutable objects can’t be changed once they are created, they are automatically synchronized/thread-safe.

11. How an object is serialized in java?

Serialization is a mechanism of converting an object into a byte stream so that the object can be easily saved to persistent storage or streamed across a communication link. An object of a class is serialized by implementing serializable interface.

12. When we should use serialization?

Serialization is used when data needs to be transmitted over the network.

You can also save object's state and convert into byte stream using Serialization

13. When the constructor of a class is invoked?

The constructor of a class is invoked when an instance of the object is created and memory is allocated for the object.

For example, in the following class, two objects are created using new keyword and hence, constructor is invoked twice.

Example

public class const_new {
  const_new() {
    system.out.println("constructor");
  }
  public static void main(String args[]) {
     const_new c1 = new const_new();
     const_new c2 = new const_new();
  }
}