Menu Close

Top 75+ OOPs Interview Questions and Answers 2023 – Devduniya

5/5 - (1 vote)

Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs. It is one of the most popular programming concepts and is widely used in the development of software applications. As such, OOP concepts are commonly covered in software development interviews. In this blog post, we will discuss some of the most frequently asked OOP interview questions and provide sample answers to help you prepare for your next interview.

Table of Contents Show

Top OOPs Interview Questions and Answers 2023

Q1. What is object-oriented programming?

Answer: Object-oriented programming (OOP) is a programming paradigm that uses objects, which are instances of classes, to represent and manipulate data. OOP is based on the concept of objects, which have properties (also called attributes or data members) and methods (also called functions or operations).

Q2. What are the four pillars of OOP?

Answer: The four pillars of OOP are:

  • Inheritance: The ability of one class to inherit properties and methods from a parent class.
  • Polymorphism: The ability of a class or its objects to take on multiple forms.
  • Encapsulation: The practice of hiding the internal details of an object from other objects and the outside world.
  • Abstraction: The practice of reducing complexity by hiding unnecessary details and showing only essential features of an object or a class.

Q3. What is inheritance and how is it used in OOP?

Answer: Inheritance is a mechanism that allows one class to inherit properties and methods from another class. This allows for a hierarchical organization of classes and can be used to create a parent-child relationship between classes. This is useful for creating classes that share common properties and methods but also have unique properties and methods.

Q4. What is polymorphism and how is it used in OOP?

Answer: Polymorphism is the ability of a class or its objects to take on multiple forms. This allows for objects of different classes to be treated as objects of a common class. For example, a method that takes an object of a parent class as an argument can also take an object of any of its child classes as an argument.

Q5. What is encapsulation and how is it used in OOP?

Answer: Encapsulation is the practice of hiding the internal details of an object from other objects and the outside world. This helps to protect the object’s data and methods from accidental or intentional modification, and allows for the implementation of the object to change without affecting other objects that use it.

Q6. What is an object and a class?

Answer: An object is an instance of a class, and a class is a blueprint for creating objects. A class defines the properties and methods that an object of that class will have, but it does not contain any data or state. An object, on the other hand, contains the data and state of a specific instance of a class.

Q7. What is the difference between a class and an object?

Answer: A class is a blueprint or template for creating objects. It defines the properties and methods that an object of that class will have. An object is an instance of a class, created at runtime. A class defines what an object should look like, while an object is a specific example of that class.

Q8. How do you define a constructor in a class?

Answer: A constructor is a special method that is used to initialize an object when it is created. It is defined using the keyword “constructor” and has the same name as the class. For example, in a class called “Person”, the constructor would be defined as “constructor()”.

Q9. How do you create an object of a class?

Answer: An object of a class can be created using the “new” keyword followed by the class name and parentheses. For example, to create an object of the “Person” class, you would use the code “let person = new Person();”

Q10. What is the difference between a static method and a non-static method?

Answer: A static method is a method that can be called directly on the class, rather than on an object of the class. This means it does not have access to the properties or methods of an individual object. A non-static method, also known as an instance method, is a method that can only be called on an object of the class and has access to the properties and methods of that individual object.

Q11. What is the difference between a static variable and a non-static variable?

Answer: A static variable is a variable that is shared by all objects of a class, while a non-static variable, also known as an instance variable, is unique to each individual object. A static variable is defined using the keyword “static” and can be accessed using the class name, while a non-static variable is defined as a property of the class and can only be accessed through an object of the class.

Q12. What is the difference between a public and a private method?

Answer: A public method is a method that can be accessed by any code outside of the class, while a private method can only be accessed by code within the class. Public methods are typically used for functionality that should be available to other parts of the program, while private methods are used for internal functionality that should not be exposed to the outside.

Q13. What is the difference between a public and a private variable?

Answer: A public variable can be accessed and modified by any class or method within the program. A private variable, on the other hand, can only be accessed and modified by methods within the same class. In other words, private variables have a more restricted scope of accessibility and are considered more secure.

Q14. What is the difference between a final and a non-final variable?

Answer: A final variable is a constant that cannot be reassigned once it has been given a value. A non-final variable, on the other hand, can be reassigned multiple times. This means that the value of a final variable is fixed and cannot be changed, while the value of a non-final variable can be changed.

Q15. What is the difference between a final and a non-final method?

Answer: A final method cannot be overridden by any subclasses, while a non-final method can be overridden by subclasses. This means that a final method can only be used in its original form and cannot be modified by subclasses, while a non-final method can be modified by subclasses.

Q16. What is an abstract class?

Answer: An abstract class is a class that cannot be instantiated, and it is meant to be a base class for one or more derived classes. An abstract class can contain both abstract and non-abstract methods. An abstract method is a method that has a declaration but no implementation. The implementation of the abstract method is provided by the subclasses.

Q17. What is an interface?

Answer: An interface is a collection of abstract methods that a class can implement. An interface defines a contract that the class must follow. The class implementing the interface must implement all the methods defined in the interface. An interface cannot be instantiated and cannot have any implementation of methods.

Q18. What is the difference between an abstract class and an interface?

Answer: An abstract class can have both abstract and non-abstract methods, and it can also have instance variables, while an interface can only have abstract methods and no instance variables. An abstract class can provide a partial implementation of a method, while an interface can only provide a method signature with no implementation. A class can extend only one abstract class, but it can implement multiple interfaces.

Q20. What is method overloading?

Answer: Method overloading is when a class has multiple methods with the same name but different parameter types or a number of parameters. This allows for methods to be reused with different inputs, making the code more flexible and easier to read. When a method is called, the Java runtime determines which method to execute based on the number and types of arguments passed to the method.

Q21. What is method overriding?

Answer: Method overriding is a feature in object-oriented programming that allows a subclass or child class to provide a specific implementation of a method that is already provided by its superclass or parent class. This is done by using the same method signature in the subclass as in the superclass. The method in the subclass will override and be called instead of the method in the superclass.

Q22. What is the difference between method overloading and method overriding?

Answer: The main difference between method overloading and method overriding is that method overloading allows multiple methods with the same name to be defined in the same class, but with different parameter lists. Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.

Q23. How do you implement multiple inheritance in Java?

Answer: In Java, multiple inheritance is not supported directly. However, it can be achieved using interfaces. A class can implement multiple interfaces, thus providing the functionality of multiple inheritances.

Q24. What is the difference between a constructor and a method?

Answer: A constructor is a special method that is used to initialize an object when it is created. It has the same name as the class and is automatically called when an object is created. A method, on the other hand, is a general block of code that can be called by other parts of the program to perform a specific task.

Q25. What is the difference between a default constructor and a parameterized constructor?

Answer: A default constructor is a constructor that is automatically provided by the compiler if no constructors are defined in the class. It takes no arguments and initializes the object’s instance variables to their default values. A parameterized constructor, on the other hand, is a constructor that takes one or more arguments and is used to initialize the object’s instance variables to specific values.

Q26. How do you create a copy of an object in Java?

Answer: In Java, an object can be copied by creating a new object and then copying the values of the fields from the original object to the new object. One way to do this is to use the clone() method of the Object class, which creates a new object that is a copy of the original object.

Q27. What is the difference between a shallow copy and a deep copy?

Answer: A shallow copy is a copy of an object that includes only the values of the object’s fields. It does not create new copies of objects referenced by the original object. A deep copy, on the other hand, creates a new copy of all objects referenced by the original object, so that the new object and the original object are completely independent.

Q28. What is a singleton class?

Answer: A singleton class is a design pattern where a class can only have one instance in the entire application. This is useful in situations where a single instance of a class needs to control the action throughout the execution of the program.
Example: A class that controls access to a shared resource, such as a printer or database connection, could be implemented as a singleton.

Q29. How do you create a singleton class in Java?

Answer: To create a singleton class in Java, the following steps are typically used:

  • Declare the constructor of the class as private to prevent other classes from instantiating it.
  • Create a static instance of the class within the class.
  • Create a static method, such as getInstance(), that returns the static instance of the class.
public class Singleton {
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}

Q30. What is a static block?

Answer: A static block is a block of code that is executed when a class is first loaded into the JVM. It is typically used to initialize static variables, and can only access static members of the class.
Example:

public class MyClass {
static int x;
static {
x = 5;
}
}

Q31. How do you use a static block in a class?

Answer: To use a static block in a class, it is placed inside the class but outside any method or constructor. It is executed when the class is first loaded and before any objects of the class are created.

Q32. What is a finalize method?

Answer: The finalize method is a method provided by the Object class in Java that is called by the Garbage Collector before an object is destroyed. It can be overridden by subclasses to perform any cleanup necessary before an object is destroyed.
Example:

class MyClass {
protected void finalize() {
// Perform cleanup here
}
}

Q33. How do you use a finalize method in a class?

Answer: To use the finalize method in a class, you can override it in your class and include any necessary cleanup code. It’s important to note that the finalize method is not guaranteed to be called and should not be used as a replacement for proper resource deallocation.

Q34. What is a Garbage Collector?

Answer: A Garbage Collector is a program in the Java Virtual Machine (JVM) that automatically frees up memory that is no longer being used by the program. It is responsible for allocating and deallocating memory, and helps to prevent memory leaks in a program.

Q35. How does the Garbage Collector work in Java?

Answer: The Garbage Collector works by periodically checking for objects in the heap that are no longer being used by the program. When it finds such an object, it marks it as eligible for garbage collection and then reclaims the memory used by that object.

Q36. What is the use of the instanceof operator?

Answer: The instanceof operator is a Java operator that is used to determine if an object is an instance of a particular class or one of its subclasses. It returns a boolean value, true if the object is an instance of the class and false otherwise.

Example:

MyClass obj = new MyClass();
if(obj instanceof MyClass) {
// do something
}

Q37. What is a package?

Answer: A package in Java is a mechanism for organizing related classes and interfaces. It allows for logical grouping of classes and interfaces, and helps to prevent naming conflicts by providing a unique namespace for each package. Packages are defined using the package keyword and can be imported into other classes using the import keyword.
Example:

package com.example;
public

Q38. How do you create a package in Java?

Answer: To create a package in Java, use the “package” keyword followed by the package name at the top of your code file. For example: “package com.example.mypackage;”

Q39. How do you import a package in Java?

Answer: To import a package in Java, use the “import” keyword followed by the package name. For example: “import com.example.mypackage.*;”

Q40. What is the difference between a static import and a regular import?

Answer: A regular import allows you to use classes from a package without specifying the package name each time. A static import allows you to use static members (fields and methods) of a class without specifying the class name each time.

Q41. What is an exception?

Answer: An exception is an abnormal event that occurs during the execution of a program, indicating that something went wrong. They are usually caused by errors in the code or unexpected inputs.

Q42. How do you handle an exception in Java?

Answer: You can handle exceptions in Java by using a try-catch block. A try block encloses the code that may throw an exception, and a catch block contains the code that will handle the exception if it is thrown.

Q43. What is a try-catch block?

Answer: A try-catch block is a control structure in Java that allows you to handle exceptions that may occur in the try block. The try block encloses the code that may throw an exception, and the catch block contains the code that will handle the exception if it is thrown.

Q44. What is a finally block?

Answer: A finally block is a block of code that will always be executed after the try and catch blocks, regardless of whether an exception was thrown or not. It is typically used to release resources or perform other cleanup tasks.

Q45. What is the difference between a checked exception and an unchecked exception?

Answer:

A checked exception is an exception that must be handled by the developer, either by catching it or declaring it in the method signature using the “throws” keyword.

An unchecked exception is an exception that does not need to be handled by the developer and typically represents a programming error. Example: FileNotFoundException is a checked exception, while NullPointerException is an unchecked exception.

Q46. What is a throw keyword?

Answer: The “throw” keyword is used to explicitly throw an exception in Java. Example: “throw new IllegalArgumentException(“Invalid value”)”

Q47. What is a throws keyword?

Answer: The “throws” keyword is used in a method signature to indicate that the method may throw a specific exception. Example: “public void readFile() throws IOException”

Q48. What is the difference between a throw and a throws keyword?

Answer: The “throw” keyword is used to throw an exception, while the “throws” keyword is used to indicate that an exception may be thrown by a method.

Q49. What is a custom exception?

Answer: A custom exception is a user-defined exception that can be used to provide more meaningful error messages.

Q50. How do you create a custom exception in Java?

Answer: To create a custom exception in Java, you can create a new class that extends the Exception class. Example: “public class MyException extends Exception {}”

Q51. What is a nested class?
Answer: A nested class is a class that is defined within another class. Example: “public class OuterClass { public static class NestedClass {} }”

Q52. What is an inner class?

Answer: An inner class is a non-static nested class. Example: “public class OuterClass { public class InnerClass {} }”

Q53. What is a local class?

Answer: A local class is a class that is defined within a method. Example: “public void myMethod() { class LocalClass {} }”

Q54. What is an anonymous class?

Answer: An anonymous class is a type of inner class in Java that does not have a name. It is typically used when creating instances of a class or interface with a small amount of functionality, such as an event listener.

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        System.out.println("Button clicked");
    }
});

Q55. What is a Lambda expression?

Answer: A Lambda expression is a short block of code that can be passed around as an argument to a method, similar to a function pointer in C or C++.

button.addActionListener(e -> System.out.println("Button clicked"));

Q56. How do you use a Lambda expression in Java?

Answer: You can use a Lambda expression in Java by providing it as an argument to a method that expects a functional interface.

button.addActionListener(e -> System.out.println("Button clicked"));

Q57. What is a functional interface?

Answer: A functional interface is an interface in Java that has exactly one abstract method. This can be used in conjunction with Lambda expressions.

@FunctionalInterface
public interface ActionListener {
    void actionPerformed(ActionEvent e);
}

Q58. What is a Stream API?

Answer: The Stream API is a collection of classes and interfaces for performing functional-style operations on streams of elements.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
System.out.println(sum);

Q59. How do you use the Stream API in Java?

Answer: You can use the Stream API in Java by obtaining a stream from a collection or other data source, and then performing operations such as filter, map, and reduce on the stream.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
System.out.println(sum);

Q60. What is a filter in the Stream API?

Answer: A filter in the Stream API is an operation that takes a Predicate (a boolean-valued function) as an argument and returns a new stream that contains only the elements that satisfy the predicate.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream().filter(n -> n % 2 == 0).forEach(System.out::println);

Q61. What is a map in the Stream API?

Answer: A map in the Stream API is an operation that takes a function as an argument and returns a new stream that contains the results of applying the function to the elements of the original stream.

List<String> words = Arrays.asList("hello", "world");
words.stream().map(String::length).forEach(System.out::println);

Q62. What is a reduction in the Stream API?

Answer: A reduction in the Stream API is an operation that combines all elements of the stream into a single result.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int product = numbers.stream().reduce(1, (a, b) -> a * b);
System.out.println(product);

Q63. What is a collector in the Stream API?

Answer: A collector is an object that accumulates elements from a stream into a summary result, such as a list or a set. For example, using the collect() method, you could collect all elements of a stream into a list:

List list = Stream.of(1, 2, 3).collect(Collectors.toList());

Q64. What is a parallel stream in the Stream API?

Answer: A parallel stream is a stream that can process elements in parallel using multiple threads. For example, you could use the parallelStream() method to create a parallel stream of a list:

List list = Arrays.asList(1, 2, 3, 4, 5);
list.parallelStream().forEach(System.out::println);

Q65. What is the difference between a parallel and a sequential stream?

Answer: A parallel stream uses multiple threads to process elements in parallel, whereas a sequential stream processes elements one at a time in a single thread. Parallel streams can be faster for large data sets, but may not be as predictable in terms of the order of elements being processed.

Q66. What is a reference in OOP?

Answer: In object-oriented programming, a reference is a variable that holds the memory address of an object. For example, you could create an object and store a reference to it in a variable:

Person person = new Person(“John”);

Q67. What is a weak reference?

Answer: A weak reference is a reference that does not prevent an object from being garbage collected. This means that the object can be removed from memory if the only references to it are weak references and there is not enough memory.

Q68. What is a soft reference?

Answer: A soft reference is a reference that is less strong than a regular reference and allows an object to be garbage collected when the JVM needs memory. Soft references are typically used for caching.

Q69. What is a phantom reference?

Answer: A phantom reference is a reference that is even weaker than a soft reference and is used to track when an object is about to be garbage collected. Phantom references must be used in conjunction with a ReferenceQueue. When an object is a garbage collected, its phantom reference is added to the queue, allowing the application to take some action.

Q70. What is a proxy pattern in OOP?

Answer: The proxy pattern in OOP is a design pattern that allows for the creation of a surrogate object that controls access to a separate, underlying object. This can be used for security, caching, or other purposes. For example, a proxy object might be used to control access to a sensitive resource, such as a file or database.

Q71. How do you implement the proxy pattern in Java?

Answer: To implement the proxy pattern in Java, you can create a proxy class that extends or implements the same interface as the underlying object, and then use that proxy class to control access to the underlying object.

Q72. What is the decorator pattern in OOP?

Answer: The decorator pattern in OOP is a design pattern that allows for the addition of new behavior or responsibilities to an existing object, without modifying its original class. This can be done by wrapping the original object in a decorator object that adds the new functionality. For example, you might use the decorator pattern to add logging functionality to an existing class, without modifying the original class.

Q73. How do you implement the decorator pattern in Java?

Answer: To implement the decorator pattern in Java, you can create a decorator class that implements the same interface as the original class, and then use that decorator class to add new functionality to the original class.

Q74. What is the adapter pattern in OOP?

Answer: The adapter pattern in OOP is a design pattern that allows for the adaptation of one interface to another so that classes that are not compatible can work together. This can be done by creating an adapter class that implements the desired interface and then using that adapter class to adapt the original class to the desired interface. For example, you might use the adapter pattern to adapt a legacy system to work with a new system.

Q75. How do you implement the adapter pattern in Java?

Answer: To implement the adapter pattern in Java, you can create an adapter class that implements the desired interface, and then use that adapter class to adapt the original class to the desired interface.

Q76. What is the observer pattern in OOP?

Answer: The observer pattern in OOP is a design pattern that allows for the creation of objects that can be notified of changes to other objects. This can be done by creating observer objects that listen for changes to other objects, and then take appropriate action when a change occurs. For example, you might use the observer pattern to notify a user of new messages in an email program.
To implement the observer pattern in Java, you can create observer objects that implement the Observer interface and then register those observer objects with the objects they should listen to. The object can then notify the observers when changes occur.

Conclusion:

In conclusion, understanding and being able to apply the concepts of OOP can be an important aspect of a software developer’s job. Familiarizing yourself with common OOP interview questions and being able to provide clear and concise answers can help demonstrate your understanding and knowledge of the subject to potential employers. Additionally, having a solid understanding of OOP can help you write more efficient, organized, and maintainable code in your work as a developer.

If you have any queries related to this article, then you can ask in the comment section, we will contact you soon, and Thank you for reading this article.

Follow me to receive more useful content:

Instagram | Twitter | Linkedin | Youtube

Thank you

Suggested Blog Posts

Leave a Reply

Your email address will not be published.