top of page

50 Java Interview Questions for Experienced - Classes, Constructors & Objects

Updated: Dec 17, 2023


Java Interview Questions for Experienced - Classes, Constructors & Objects

In this blog post, we will delve into a curated set of Java interview questions for experienced professionals. "Classes, Constructors, and Objects Interview Q&A" (Basic Java interview questions) provides valuable insights and answers related to Java object oriented programming interview questions.


1. Question: What is a class in Java?

Answer: A class in Java is a blueprint or template for creating objects. It defines the structure and behavior of objects of that class.


2. Question: How do you define a class in Java?

Answer: To define a class in Java, you use the class keyword followed by the class name and class body enclosed in curly braces.

public class MyClass {

// Class members go here

}


3. Question: What is an object in Java?

Answer: An object is an instance of a class. It represents a real-world entity and can have state (attributes) and behavior (methods).


4. Question: How do you create an object in Java?

Answer: You can create an object in Java using the new keyword, followed by the class constructor. MyClass myObject = new MyClass();

5. Question: What is a constructor in Java?

Answer: A constructor is a special method in a class used to initialize objects. It has the same name as the class and is called when an object is created.


6. Question: What is the default constructor in Java?

Answer: If a class doesn't define any constructors, Java provides a default constructor with no arguments. It initializes the object with default values.


7. Question: Can a class have multiple constructors in Java?

Answer: Yes, a class can have multiple constructors with different parameters. This is called constructor overloading.


8. Question: What is the purpose of the this keyword in a constructor?

Answer: The this keyword is used to refer to the current instance of the class. It can be used in a constructor to disambiguate between class members and constructor parameters with the same name.


9. Question: What is a parameterized constructor?

Answer: A parameterized constructor is a constructor that takes one or more parameters. It allows you to initialize object properties with values passed as arguments when the object is created.

10. Question: What is the difference between a constructor and a method in Java? Answer: Constructors are special methods used for object initialization and have the same name as the class. Methods are regular functions defined within a class and are used for performing actions or operations on objects.

11. Question: How can you call one constructor from another constructor in the same class? Answer: You can use the `this()` keyword to call another constructor from within a constructor in the same class. This is known as constructor chaining.

12. Question: What is the purpose of the static keyword in Java? Answer: The `static` keyword is used to define class-level members (variables and methods) that belong to the class itself rather than to instances of the class.


13. Question: Can you create an object of a class that has a private constructor and what is its use?

Answer: No, you cannot create an object of a class with a private constructor from outside the class. However, the class itself can create objects of its own using the private constructor.

Common use cases for a class that has a private constructor: Singleton Pattern: One of the most common uses of a private constructor is to implement the Singleton design pattern. In this pattern, a class ensures that it has only one instance, and that instance can be accessed globally. The private constructor prevents external code from creating multiple instances of the class. Access to the single instance is typically provided through a public static method. public class Singleton {

private static Singleton instance;


private Singleton() {

// Private constructor to prevent instantiation

}


public static Singleton getInstance() {

if (instance == null) {

instance = new Singleton();

}

return instance;

}

}


14. Question: What is the toString() method in Java? Answer: The `toString()` method is a built-in method in the `Object` class that is overridden in most Java classes. It returns a string representation of the object, which is often used for debugging and printing.


Core Java Programming

Java Back-End Development


15. Question: What is method overloading in Java? Answer: Method overloading is a feature in Java that allows you to define multiple methods with the same name in a class, as long as they have different parameter lists (different types or different numbers of parameters). 16. Question: What is method overriding in Java? Answer: Method overriding is a feature in Java that allows a subclass to provide a specific implementation for a method that is already defined in its super class. The overridden method has the same name, return type, and parameters.

17. Question: Can a constructor be overridden in Java? Answer: Constructors cannot be overridden in Java. Each class has its own constructor, and constructors are not inherited.

18. Question: What is the super keyword used for in Java? Answer: The `super` keyword is used to refer to the super class (parent class) of a subclass. It can be used to call super class constructors or methods.


19. Question: What is encapsulation in Java?

Answer: Encapsulation is the concept of restricting access to the internal state (variables) of an object and exposing it only through public methods. It helps maintain data integrity and allows controlled access to object properties.


20. Question: What is a getter and setter method in Java? Answer: Getter methods (also known as accessor methods) are used to retrieve the values of private fields, while setter methods (mutator methods) are used to set the values of private fields. They are often used to implement encapsulation.


21. Question: What is inheritance in Java? Answer: Inheritance is a mechanism in Java that allows a class (subclass or derived class) to inherit properties and behaviors (fields and methods) from another class (super class or base class).

22. Question: What happens when an object of the subclass is created?

Answer: When an object of a subclass is created, the constructor of the super class is automatically called before the constructor of the subclass. This is known as constructor chaining. 23. Question: Can you instantiate an abstract class in Java? Answer: No, you cannot create an instance of an abstract class in Java. Abstract classes are meant to be subclassed, and you can only create objects of concrete (non-abstract) subclasses.


24. Question: What is the difference between the equals() method and the == operator in Java? Answer: The `equals()` method is used to compare the content or values of objects for equality. The `==` operator, on the other hand, compares object references to determine if they refer to the same object in memory. 25. Question: How do you prevent a class from being subclassed in Java? Answer: You can prevent a class from being sub classed by declaring it as `final`. A `final` class cannot be extended by other classes.


26. Question: What is the purpose of the final keyword in Java? Answer: The `final` keyword can be applied to variables, methods, and classes in Java. When applied to a variable, it makes the variable a constant (unchangeable). When applied to a method, it prevents method overriding in subclasses. When applied to a class, it prevents the class from being extended.


27. Question: What is a static block in Java, and when is it executed? Answer: A static block is a block of code enclosed in curly braces and marked with the `static` keyword. It is executed when the class is loaded into memory, typically before any instances of the class are created. Static blocks are often used for static initialization.

28. Question: What is the purpose of the finalize() method in Java? Answer: The `finalize()` method is a method in the `Object` class that can be overridden by a class to perform cleanup operations on an object before it is garbage collected. However, it is rarely used in modern Java programming, and resource management is usually done using other techniques.

29. Question: Can you have a constructor in an interface in Java? Answer: No, you cannot have a constructor in an interface in Java. Interfaces define a contract of methods to be implemented by classes, but they cannot have constructors.

30. Question: What is the purpose of the static keyword in a method signature? Answer: The `static` keyword in a method signature indicates that the method belongs to the class itself, rather than to instances of the class. Static methods can be called using the class name without creating an object.


Core Java Programming

Java Back-End Development


31. Question: What is the difference between composition and inheritance in Java? Answer: Composition is a design principle where a class contains objects of other classes as members, while inheritance is the mechanism where a class inherits properties and behaviors from another class. Composition promotes code reusability without creating tight coupling, whereas inheritance can lead to tight coupling and can limit flexibility.

32. Question: What is the Object class in Java, and why is it important? Answer: The `Object` class is the root class for all classes in Java. It provides basic functionality and methods, such as `equals()`, `hashCode()`, and `toString()`, that can be overridden in user-defined classes. Understanding the `Object` class is important for effective Java programming.

33. Question: What is a nested class in Java? Answer: A nested class is a class defined within another class. It can be either a static nested class or an inner (non-static) class. Nested classes are often used for encapsulation and organization of related code.

34. Question: What is the instanceof operator used for in Java? Answer: The `instanceof` operator is used to test whether an object is an instance of a particular class or interface. It returns `true` if the object is an instance of the specified type or one of its subclasses/interfaces.

35. Question: What is the purpose of the transient keyword in Java? Answer: The `transient` keyword is used to indicate that a variable should not be serialized when an object is serialized (e.g., when using Java's object serialization). It is often used for variables that are not relevant to the object's persistent state.

36. Question: What is the difference between shallow copy and deep copy of objects in Java? Answer: A shallow copy of an object copies the object itself and its immediate references, while a deep copy copies the object and all objects referenced by it, recursively. Shallow copies result in multiple objects sharing some references, whereas deep copies create entirely separate copies of the object and its dependencies.

37. Question: What is the purpose of the clone() method in Java? Answer: The `clone()` method is used to create a copy of an object. It's part of the `Cloneable` interface and must be overridden in user-defined classes to specify how the cloning should be performed.

38. Question: What is an anonymous inner class in Java? Answer: An anonymous inner class is an inner class without a name. It is often used for creating small, one-time-use classes, especially when implementing interfaces or extending classes in a concise way.

39. Question: What is the static import statement in Java? Answer: The `static` import statement allows you to import static members (fields and methods) of a class directly into your code, so you can use them without prefixing with the class name.

40. Question: What is the purpose of the assert statement in Java? Answer: The `assert` statement is used for debugging and testing purposes. It allows you to check whether a given condition is `true`, and if not, it throws an `AssertionError`.


41. Question: What is the difference between a constructor and a factory method in Java? Answer: A constructor is used to create and initialize objects of a class, while a factory method is a static method used to create and return objects. Factory methods provide more flexibility in object creation and can return cached or pre-configured instances.

42. Question: What is a singleton pattern in Java, and how do you implement it? Answer: The singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. To implement it, you typically create a private constructor, a private static instance variable, and a public static method to access the instance.

43. Question: What is the purpose of the this reference in Java? Answer: The `this` reference is used to refer to the current instance of a class. It can be used to access instance variables or call instance methods. It is often used to disambiguate between instance variables and method parameters with the same name.

44. Question: How do you prevent a method from being overridden in Java? Answer: To prevent a method from being overridden in Java, you can declare the method as `final` in the super class. Sub classes will not be able to override or change the method implementation.

45. Question: What is dynamic method dispatch in Java? Answer: Dynamic method dispatch is a mechanism in Java where the method to be executed is determined at runtime based on the actual object type rather than the reference type. It allows polymorphic behavior and is essential for method overriding.


46. Question: What is the volatile keyword used for in Java? Answer: The `volatile` keyword is used to declare a variable as volatile. Volatile variables are guaranteed to be visible to all threads and are not subject to certain compiler optimizations. They are often used in multithreaded programming to ensure proper visibility of variables.

47. Question: What is the purpose of the enum keyword in Java? Answer: The `enum` keyword is used to define enumerated types, which are a set of named constants. Enums provide a way to represent a fixed set of values and improve code readability.

48. Question: What is an abstract class in Java, and when should you use it? Answer: An abstract class is a class that cannot be instantiated and is meant to be sub classed. It can have abstract (unimplemented) methods that must be implemented by its sub classes. Abstract classes are used when you want to provide a common interface and some default behavior for related classes.

49. Question: What is method hiding in Java, and how is it different from method overriding? Answer: Method hiding occurs when a subclass defines a static method with the same name and signature as a static method in its superclass. Unlike instance methods, static methods are not overridden in Java; instead, they are hidden. Here's an example of method hiding in Java:

class Superclass {

static void staticMethod() {

System.out.println("Static method in Superclass");

}

}


class Subclass extends Superclass {

static void staticMethod() {

System.out.println("Static method in Subclass");

}

}


public class MethodHidingExample {

public static void main(String[] args) {

Superclass obj1 = new Superclass();

Subclass obj2 = new Subclass();


Superclass.staticMethod(); // Calls the static method in Superclass

Subclass.staticMethod(); // Calls the static method in Subclass


obj1.staticMethod(); // Calls the static method in Superclass

obj2.staticMethod(); // Calls the static method in Subclass

}

}

In this example, both the Superclass and Subclass have a static method named staticMethod. When you call staticMethod on objects of these classes or on the classes themselves, the method that gets executed depends on the reference type, not the actual object type.

50. Question: Can you provide an example of method overloading in Java?

Answer: Here's an example of method overloading in Java:

public class Calculator {

public int add(int a, int b) {

return a + b;

}


public double add(double a, double b) {

return a + b;

}


public String add(String a, String b) {

return a.concat(b);

}

}


In this example, the `add` method is overloaded with different parameter types (int, double, and String) to perform addition or string concatenation based on the data types of the arguments.

46 views0 comments

Comments


bottom of page