Ramya Shankar | 08 Aug, 2023

50+ OOP Interview Questions and Answers in 2024

 

OOP stands for object-oriented programming and it is one of the most impactful programming paradigms. It focuses on classes and objects as opposed to functions and procedures. Its principal goal is to bind data and objects together, making it easier to operate on them.

With OOP, each object consists of data in the form of fields and code in the form of procedures or methods. Some widely used object-oriented programming languages are C++, Objective C, Python, Perl, Java, Ada, among others. 

It’s important to know more about this as oops interview questions are quite common. Most companies seek developers who are proficient in object-oriented approaches and patterns. So, if you’re planning to appear for an interview with even a semi-established firm, you must possess an in-depth knowledge of OOP concepts.  

Here, we highlight some commonly asked object-oriented programming interview questions. We have categorized interview questions into two categories: basic OOPs interview questions and advanced OOPs interview questions. 

Let’s get started!

Basic OOPs Interview Questions

1. What is object-oriented programming (OOP)?

Object-oriented programming (OOP) is a model based on classes and objects instead of functions and stored procedures. Objects are real-world entities defined via classes having specific behavior and characteristics, and a class is referred to as a blueprint for creating objects.

A Class is defined as the blueprint for the specific object and is a user-defined datatype. A class consists of variables, methods, member functions, and others. You cannot consider the class as the data structure as a logical entity. These classes do not take up memory in run time. 

Objects are real-world entities consisting of behavior, attributes, and properties that define the object. It is an instance of the class defined by the user, and it takes up memory, unlike the class itself.

For example:

  • Class: Various car models, such as Toyota, Hyundai, Volkswagen etc.
  • Object: The specific car model
  • Characteristics: Color, speed, mileage, etc.
  • Behavior: How to operate and maintain the car, and so on

Each object of the class can have different characteristics based on the properties that define the object.

2. Why should you use OOP?

OOP provides several benefits while designing programs. Some of these are:

  • Clarity in programming which can help solve complex problems more easily
  • The reuse of the specific code used in inheritance, thus eliminating to recode certain elements of design 
  • Encapsulation, which binds the data and code together to ensure security
  • Can help in breaking down complex problems into more straightforward and small parts that can be solved individually and independently
  • Polymorphism, which grants flexibility by creating multiple forms of an entity

3. What are the pillars of the OOP concept?

The following are the main pillars of OOP:

  • Inheritance: Inheritance allows classes to inherit the characteristics of another class.
  • Encapsulation: This is specified as the attribute of an object that hides crucial data. This keeps the data hidden for members of the class. The specifiers define the access of the object’s attribute in the code.
  • Polymorphism: This lets you perform a single task in different ways. It is implemented via interfaces, where we define one interface, which is then implemented many times.
  • Data Abstraction: Using this feature, you can hide crucial information from the outside world and provide only the necessary details.

4. What are the limitations of the OOP paradigm?

OOP does come with some limitations. These are:

  • An intensive testing process which can be time consuming
  • Without proper class documentation, you might not understand the code
  • Due to the extensive program size, it consumes a large amount of memory

5. State the difference between OOP and structured programming.

The following table describes the differences between both programming models:

Object-oriented Programming

Structural Programming

Bottom-up approach

Top-down approach

Implements data hiding

Does not ensure data hiding

Can handle complex problems

Can mostly handle only moderate problems

Allows code reusability

Does not facilitate code reusability

More flexible

Less flexible

Primary concern is data

Primary concern is a logical structure

 

6. What programming languages use OOP?

The following languages use OOP:

  • Python
  • Java
  • Go
  • Dart
  • C++
  • C#
  • Ruby

Diagram showing programming languages that use OOP

7. What are classes and objects?

Class: The blueprint for the specific object and is a user-defined datatype. A class consists of values, known as member data or data, and some set of rules known as functions. Whenever an object is created, it automatically takes functions and data members present in the class. It is in this way that a class is a blueprint for an object. We can create as many objects as we can depending on the class. 

Objects: Real-world entities consisting of behavior, attributes, and properties that define the object. It is an instance of the class defined by the user. Objects have characteristic behavior and consume some space.

8. State the difference between class and object.

The following table highlights the differences between class and object:

Class

Object

Defined as the logical conceptual entity

Defined as the real-world entity

Binds the data and methods together

Acts like a variable of a class

Does not require memory

Take up memory

You can declare class only once

You can create multiple objects for a specific class

Uses the “class” keyword to define the class

Uses the “new” keyword for object creation

9. What is inheritance?

In general, we define inheritance as receiving the properties or behavior from the parent class to the child class. In object-oriented programming, inheritance allows us to inherit the properties of one class to another, such as methods, variables, instances, etc. This way, you can reuse the code of one class without writing the same code in another class. 

10. What are the different types of inheritance?

The different types of inheritance used in OOP are:

  • Single inheritance
  • Multiple inheritances
  • Multilevel inheritance
  • Hierarchical inheritance
  • Hybrid inheritance

Diagram of types of inheritance used in OOP

11. What is multiple inheritance?

Multiple inheritances allow users to inherit more than one base class to a specific class. Alternatively, one class or object can inherit properties from more than one parent class or parent object. Java, however, does not support multiple inheritances due to ambiguity. Instead, Java uses interfaces to achieve multiple inheritance. 

For example: 

class A

{ 
  void msg()

   {

      System.out.println("Hello");

   } 
} 
class B

{ 
  void msg()

   {

      System.out.println("Welcome");

   } 
} 
class C extends A,B

{  
  public static void main(String args[])

   { 
      C obj=new C(); 
      obj.msg(); 
  } 
}  

This will result in a compile-time error, as the compiler cannot decide which method of which class to call.

12. What is multilevel inheritance?

In multilevel inheritance, a derived class inherits the base class, and that derived class serves as the base class to other classes. For example, “motorbike” is a class that inherits the “two-wheelers'' class which is a subclass of the “vehicles'' class.

An example of multilevel inheritance: 

class Animal


  void eat()

   {

      System.out.println("eat");

   } 

class Dog extends Animal


    void bark()

    {

      System.out.println("bark");

    } 

class Pupp extends Dog


    void tail()

     {

       System.out.println("tail");

     } 

class Test


  public static void main(String args[])

   { 
      Pupp d=new Pupp (); 
      d.tail(); 
      d.bark(); 
      d.eat(); 
  }

 

13. What are the limitations of inheritance?

  • Using inheritance will increase execution time because it accesses various classes repeatedly
  • There is a tight coupling between the child and the parent class
  • If you want to make any changes to the program, you need to change parent and child classes.
  • If you do not implement the inheritance correctly, the program execution will result in errors.

14. What are the differences between extends and implements keywords?

The following table highlights the significant differences between the extends and implements keywords:

Extends

Implements

You can use this keyword for extending a class (a child can extend its parent class by inheriting the characteristics)

The implement is used by the class to implement the interface

The Subclass doesn’t need to extend all the methods of the superclass 

If a class is implementing an interface, then it has to implement all of its methods 

You can use the extends keyword for extending a single superclass

With the interface, a class can implement more than one interface

With extend, an interface can extend more than one interface

You cannot use an implement for one interface to implement another interface

Syntax:

class Child extends class Parent

Syntax:

class XYZ implements Rose

15. What is polymorphism?

Poly means many forms, and it occurs only if we have multiple classes related to each other by inheritance. We can perform a single action using multiple methods in polymorphism. Polymorphism enables us to define one interface and have multiple implementations for it. 

For example, assume you have defined a class named Vehicle with a speed method, but there is no need to define this method as different vehicles have different speeds. You can define this method in the subclasses with different definitions.

Java comes with two different types of polymorphism: 

  • Compile-time polymorphism: implemented via method overloading of operator overloading. Multiple methods are defined with the same name, and the compiler decides which function to call at the compile time depending upon the parameters used.

 

class Com_pol
{
  // 1st method
  public int sum(int x, int y){
    return x+y;
  }
  // 2nd method
  public int sum(int a, int b, int c)
  {
    return a+b+c;
  }
    }
class Test_sum
{
  public static void main(String[] args)
{
  Com_pol demo=new Com_ Pol();
  // call method 1
  System.out.println(demo.sum(2,3));
  //calls method 2
  System.out.println(demo.sum(2,3,4)); 
  }
}

In the above example, the compiler will check which method to call and call them to compile.

  • Runtime polymorphism: implemented via method overriding.
class Veh
{
  public void run()
  {
    System.out.println("Any vehicle should run!!");
  }
}
class Scooter extends Vehicle
{
  public void run()
  {
    System.out.println("Scooter can run too!!");
  }
}
class Test_demo

{
  public static void main(String[] args)

  {
    Veh v= new Scooter();
    v= new Veh();
    v.run();
  }
}

16. What is static and dynamic polymorphism?

Static polymorphism: This type of polymorphism occurs at compile-time. Method overloading is an example of static polymorphism.

Example:

class Demo

int var=100;

  public static void main(String args[])

 { 
    Demo b = new Demo();
    System.out.println(b.var); 
  } 

 

 

Output:

100

 

Dynamic polymorphism: Runtime polymorphism or dynamic polymorphism is resolved during runtime. Method overriding is an example of dynamic polymorphism.

Dynamic binding example:

class Simple

int var=100;
}

class Child_Simple extends Simple

int var=30;
 
  public static void main(String args[])

    Simple b = new Child_Simple(); 
    System.out.println(b.var); 
  } 

 

 

Output:

100

 

17. What is method overloading?

Method overloading allows you to define many methods with the same name, but with parameters that differ from other methods defined within the same class.

Example:

class Sum

  static int add_num(int a, int b)
  {
    return a+b;
    } 
  static double add_num(double a, double b)
  {
    return a+b;
    } 

class Demo

  public static void main(String[] args)
  { 
      System.out.println(Sum.add_num(1,2)); 
      System.out.println(Sum.add_num(12.3,12.6)); 
    }
}  

 

Output:

 

3
24.9

 

18. What is method overriding?

Method overriding allows you to redefine the base class method. The method that has been overridden will have the exact definition, signature, number of arguments, and return type. 

class Vehicle

  void run()
{
System.out.println("Running");


//Child class 
class Scooter extends Vehicle

  void run()
  {
    System.out.println("Scooter is running");
  }

public static void main(String args[])

    Scooter obj = new Scooter();
    obj.run();
}
}

 

Output:

Scooter is running

 

19. What is operator overloading?

Operator overloading means implementing the operators using user-defined types depending on the arguments passed along.

20. What is encapsulation?

Encapsulation is binding everything together required to carry out a specific task within a capsule and making that capsule available to the user. In short, all the essential data and methods are bound together, and all the unnecessary details are kept hidden from the normal user. The following examples explain this concept.

Pack file:

package Simple_pack; 
public class Pack


  private int var;
  public int getVar()

   {
      return var; 

   }
public void setVar(int v)

 {

   var=v;

 }
}  

 

Simple file: 

package Simple_pack;
//import demo_pack.*;
class Sim 

{
  public static void main(String args[])

   { 
      Pack d=new Pack();
      d.setVar(6);
      System.out.println(d.getVar());
  } 

 

21. What is association?

It specifies the object’s relationship. You can associate one object with one or many objects. The following types of association relationships exist:

  • One to one
  • One to many
  • Many to one
  • Many to many

Advanced OOP Interview Questions

22. What is an exception?

An exception is an event that disrupts the normal working of the code. You can handle these exceptions in Java to continue execution. There are various types of pre-defined exceptions in Java, and it provides exception handling to manage the raised exceptions using try-catch blocks.

23. What is exception handling and what are its advantages?

Exception handling is the most significant procedure in Java for handling unexpected runtime errors. With it, you can manage runtime errors that occur during the execution of the program. 

The advantages of exception handling are that you will be able to maintain normal program flow with exception handling. For example, if any error occurs in a particular part of the program, it will not impact the rest of the program if we handle that exception using try-catch blocks. 

24. What are the different types of exceptions in Java?

The following are the three different types of exceptions in Java: 

Checked exception:

Checked Exceptions in Java are compile-time exceptions since they are checked at compile-time. In addition, the Java compiler verifies whether a program handles the exception or not. If the program does not handle checked exceptions, it results in a compilation error. 

Unchecked exception:

Unchecked exceptions in Java are run-time exceptions since they are checked at runtime. These exceptions are opposite to checked exceptions, and the Java compiler will not check these exceptions.

Error:

Error is irrecoverable and will occur if the flow of the program fails.

25. What are the different keywords used in exceptions?

The following are the main keywords used in exception handling:

Try: The try keyword will specify the code block to place the exception code. You cannot use the try block alone; it must be followed by either the catch block or the finally block.

Catch: This block will handle the exception thrown within the try block. Also, you cannot use the catch block alone; it should be preceded with the try code block and followed by the finally block. 

Finally: This block will be executed irrespective of the exception raised. 

Throw: This keyword will be used to throw an exception.

Throws: This keyword is used to declare exceptions in a block. 

26. Explain the concept of garbage collection.

Object-oriented programming is object-based. Each object takes up some memory as you can create multiple objects of a class, so there will be a considerable amount of space taken up by objects. So, if you fail to manage the memory correctly, it might lead to memory-related errors and crash your system.

OOP comes with a concept called garbage collection that helps handle the program’s free memory that has been consumed.

27. Does the class consume memory space?

No, the class does not consume any of the space in memory. Instead, it will be saved as a file on your hard drive. It’s when we create the objects of that class that memory allocation takes place. A Java class is just a blueprint for objects. 

28. Explain tokens in Java.

The Java compiler breaks the line of code into text or words known as Java tokens. These tokens are considered the smallest element of the Java program and are separated by the delimiters. It is helpful for compilers to detect errors. But these delimiters are not part of the Java tokens.

 

class Veh
{
  public void run()
  {
    System.out.println("Any vehicle should run!!");
  }
}
class Scooter extends Vehicle
{
  public void run()
  {
    System.out.println("Scooter can run too!!");
  }
}
class Test_demo

{
  public static void main(String[] args)

  {
    Veh v= new Scooter();
    v= new Veh();
    v.run();
  }
}

In the above code snippet, public, class, Test1, {, static, void, main, (, String, args, [, ], ), System, etc. are all Java tokens.

29. What are the different types of variables in OOP?

The following are the three different types of variables in OOP:

  • Instance variables: These variables are declared within the class. But they will always be outside the method block, code block, and constructors. These variables are upon the object creation, and you can easily access them by calling them directly. 
  • Static variables: These variables are always declared using static keywords, and they are declared outside the method, code block, and constructor and stored within the static memory. For accessing the static variables, you need to use the class_name.var_name.
  • Local variables: These are method-level variables that are declared within the method block constructor, and its visibility is limited to only the method within which it is declared. 

30. Do you always have to create objects from a class?

If the base class contains non-static methods, you should create the object for that class to access the methods of that class. But if the class contains static methods, you can simply call the class methods using the class name to access the class method without creating an object for that class.

31. What is an abstract class?

An abstract class consists of abstract methods with only the declaration body but without definition. For using these methods in a subclass, you must define them exclusively.

32. What is coupling?

It refers to when different classes depend on each other and contain information. If one class has the information of another class in detail, then it is specified as a strong coupling. Using access modifiers, you can define the visibility of classes, methods, or any variable. For weaker coupling, interfaces are used.

33. What is cohesion?

Cohesion refers to how a component performs a specific task. A strong, cohesive method will simply perform the specified task, while a weak cohesive method will break the single task into many small tasks and then perform them. The Java.io package is highly cohesive, while the java.util is not as cohesive. 

34. What is composition?

You can achieve an association via composition. Unlike aggregation, it represents a strong object relationship between the dependent and the independent object. In this scenario, the dependent object does not exist and will get deleted if the parent object is deleted. 

35. What are the different ways to initialize an object?

We can initialize objects using:

  • The reference variable
  • A method
  • A constructor

36.  What are predefined methods in Java?

The Java class library has several predefined methods or built-in methods. You can directly use these methods within the program at any time. These methods perform specific, commonly used tasks. For example, length(), equals(), compareTo() are three predefined methods within the Java library. 

Example:

class Veh
{
  public void run()
  {
    System.out.println("Any vehicle should run!!");
  }
}
class Scooter extends Vehicle
{
  public void run()
  {
    System.out.println("Scooter can run too!!");
  }
}
class Test_demo

{
  public static void main(String[] args)

  {
    Veh v= new Scooter();
    v= new Veh();
    v.run();
  }
}

Output:

square: 16

 

In the above example, main(), print(), and max() are predefined methods, so there is no declaration required. 

37. What is the abstract method?

An abstract method does not have the body, and the abstract class implementing the interface will provide the body definition of that method. You can use the ‘abstract’ keyword to create an abstract method.

Example:

abstract class Dem
{ 
  abstract void display(); 
} 
public class MyClass extends Dem
{ 
//implementing method 
    void display() 
    { 
      System.out.println("Bye"); 
    } 
    public static void main(String args[]) 
    { 
        Dem obj = new MyClass(); 
        obj.display(); 
    } 
}  

Output:

 

Bye

 

38. What are some points to consider while creating an abstract class?

Consider the following while creating an abstract class:

  • Always declare the abstract class with the abstract keyword
  • An abstract class can have abstract and non-abstract methods
  • We cannot instantiate an abstract class
  • An abstract class can have constructors and static methods also
  • It can also have final methods

39. What is a destructor?

A destructor is a method that is automatically called whenever an object is destroyed.

The destructor clears up the heap space consumed by the object. It will also close the opened files and database connections related to that object.

40. What is the difference between abstraction and encapsulation?

Blue chart depicting differences between abstraction and encapsulation

Abstraction allows you to create a general structure of a class, and it is up to the implementers to implement the interface. On the other hand, encapsulation defines the restrictions of an object and its member variables and methods.

Abstraction is implemented with the help of interface and abstract class, while encapsulation is implemented using different access level modifiers, namely public, protected, and private, or no modifier at all.

41. What is the difference between class and structure?

Class

Structure

Class is a group of objects sharing properties

Structure is defined as a collection of different data types

Contains data members and member functions

Contains data members only

Features inheritance

Does not feature inheritance

You cannot initialize data members directly

You can initialize data members directly

By default, all members are private

By default, all members are public

For defining a class, we will use the class keyword

We will use the struct keyword for defining a structure

Useful for handling complex data structures

Useful for the small data structures

 

42. What are some rules for creating a constructor?

The following are a few rules to keep in mind when creating a constructor in Java:

  • It does not have a return type
  • It is declared with the same name as the Class name
  • A constructor cannot be static, abstract, or final

43. What is the difference between the copy constructor and the assignment operator?

Copy Constructor

Assignment Operator

It is a type of overloaded constructor

It is an operator

Creates a copy of an existing object

Assigns the object’s value to another existing object

Useful when a new object is created with an existing object

Useful when you want to assign an existing object to a new object

Both objects hold separate memory locations

Both objects share the same memory

 

44. What are the different levels of data abstraction?

Diagram of types of data abstraction

There are three levels of data abstraction, as described below:

  • Physical level: The lowest level of data abstraction that defines how the data is actually stored in memory
  • Logical level: It specifies the information stored in the database in tabular forms along with data entity-relationship in simple structures. It describes what data is stored in a database.
  • View level: It is the top level of data abstraction. It is an actual database visible to the user. It makes the database more accessible to an individual user.

45. Can you overload a constructor?

Yes, we can overload a constructor by passing a different parameter list to each constructor. The Java compiler calls a constructor depending upon the number of parameters passed and their data types.

46. Can you overload the main method in Java?

Yes, we can overload the main() method in Java, but the method signature must be different. 

For example:

class Over_Main   
{   
  public static void main(int a)  //overloaded main method   
  {   
      System.out.println(a);   
  }   
  public static void main(String args[])   
  {      
      System.out.println("call main method");   
      main(4);   
  }   
}    

47. What operators cannot be overloaded?

  • Scope Resolution Operator (::)
  • Ternary Operator (? :)
  • Member Access or Dot Operator (.)
  • Pointer to Member Operator (.*)
  • sizeof operator

Java OOPs Interview Questions

48. What are access modifiers in Java?

There are four different types of access modifiers in Java, as described below. 

  • Private: The scope of the private modifier limits access to only within the class, and not outside the method and constructor block
  • Default: The default scope only limits access within the package. You cannot access the default data members from outside of the package. If you do not define a modifier, it will take this form by default.
  • Protected: The protected scope will limit access to only within the package. You can access these variables outside the package using the class, and you cannot access the protected modifier without using the child class.
  • Public: You can access public modifiers anywhere within any class, package, sub-package, etc.

49. What is the difference between interface and abstract?

Abstract class

Interface

It can consist of both abstract and non-abstract methods

It consists of abstract, default, or static methods

Does not support multiple inheritance

Does support multiple inheritance

Variables can be declared as static, final, non-final, non-static

Variable can only be declared as static and final

Provide interface implementation

Does not provide an abstract class implementation

You need to declare a class with the abstract keyword

You need to declare an interface with the interface keyword

This can be extended and implement multiple interfaces

This can only extend another interface

 

Example with abstract class and interface:

 

interface demo
{
  void display();
  void cover();
}

abstract class mask implements demo
{
  public void display()
  {
      System.out.println("welcome abstract display");
    }
}

class Sim extends mask
{
  public void display()
  {
      System.out.println("welcome main display");
    }
    public void cover()
    {
      System.out.println(" cover");
    }

    public static void main(String args[])
    { 
      demo de= new Sim(); 
      de.display();
      de.cover();
    } 
} 

Output:

welcome main display
welcome abstract display
cover

 

50. What is the final keyword?

Final is a keyword used to restrict the user. If data members are defined using the final keyword, you cannot change its value. You can use the ‘final’ keyword in the context of the variable, method, and class. 

For example, if a variable is declared as final, it will act as a constant. 

Example:

class Test

{ 
  final int speed=10; 
  void run()

  { 
    speed=410; 
  } 
  public static void main(String args[])

  { 
    Test obj=new  Test();  

    obj.run(); 
  } 
}

Output:

Compile-time error

In the above example, speed is the final variable, and we are trying to change its value in the run method. Thus, it will give a compile-time error.

51. What is the final method in Java?

If a method is specified as final in a class, you cannot override it in its subclass. You will get a compile-time error if you override the final method in the subclass, as shown in the example below.

Example:

class Demo
{ 
  final void run()
  {

    System.out.println("running");
  } 
} 
class Big extends Demo
{ 
  void run()
  {
      System.out.println("running safely");
  } 
   
  public static void main(String args[])
  { 
    Big b= new Big(); 
    b.run(); 
  } 
}  

Output:

Compile-time error

52. What is the final class?

If you declare any class with the final keyword, you cannot extend it and access its data member. You will get a compile-time error if you extend the final class, as shown in the example below.

Example:

final class Demo{} 
 
class Bike extends Demo

{ 
  void run()

  { 

    System.out.println("running");

  } 
   
  public static void main(String args[])

  { 
      Bike b= new Bike(); 
      b.run(); 
  } 
}  

Output:

Compile-time error

53. What is the super keyword in Java?

In Java, the super keyword is used for the immediate parent class. An instance of the superclass will automatically be created whenever you create an instance of its subclass. You can then inherit the superclass methods and variables using the super keyword. 

You can refer to the instance variable, class methods, constructor, and immediate parent class with super keywords. There are some examples listed below to understand this better.

How to refer to the parent’s class instance variable

You can use this keyword to solve the ambiguity if the superclass and the subclass have the same data member. 

Example:

 

class Animal
{ 
  String col="Black"; 
} 
class Dog extends Animal
{ 
  String col="Beige"; 
  void Col()
  { 
    System.out.println(col);
    System.out.println(super.col);
  } 
} 
class Demo
{ 
    public static void main(String args[])
    { 
          Dog s=new Dog(); 
          s.printCol(); 
      }
}

Output:

Beige
Black

 

In the above example, both the child and the parent class have the same data member, Col. By default, the value of the current class data member will be displayed, but if you specify the super keyword, it will display the value of the parent class.

Invoking the parent’s class method

For invoking the parents class method, you need to specify the super keyword with the method. It is helpful if both the parent class and the child class have the method with the same name. If the method is overridden, you can access the parent’s class method using the super keyword below.

Example:

class Animal


  void drink()

   {

      System.out.println("drinking");

   } 

class Dog extends Animal


  void drink()

   {

      System.out.println("eat");

   } 
  void run()

   {

      System.out.println("run");

   } 
  void demo_function()

   { 
      super.drink(); 
      run(); 
    } 

class De


  public static void main(String args[])

   { 
    Dog de=new Dog(); 
    de.demo_function(); 
    }

}

 

 

Output:

drinking
run

 

Invoking the parent’s class constructor

For invoking the parent’s class constructor, you can use the super keyword, as shown below.

Example:

class Animal


  Animal()

   {

     System.out.println("animal class");

   } 

class Dog extends Animal


  Dog()

   { 
      super(); 
      System.out.println("dog class"); 
  } 

class Demo


    public static void main(String args[])

    { 
      Dog d=new Dog(); 
    }

}  

 

Output:

animal class
dog class

54. What is a constructor?

In OOP, a constructor is a special block of code or a method used to initialize the newly created object of a particular class. A constructor has the same name as that of the class name. When we create an object in a class, a constructor gets called automatically. When the constructor is called, memory gets allocated to the object. 

For example, for a class with the name “Demo”, a constructor is defined as:

Demo de= new Demo();

55. What is the default constructor in Java?

A constructor without any parameters is referred to as the default constructor. If you do not pass any value, the constructor will display the default value of the variable data type.

Syntax:

<class_name>()
{}

 

Example:

class Demo1

{ 
  Demo1()
  {

    System.out.println("Hello");
  } 
  public static void main(String args[])

  { 
    Demo1 b=new Demo1(); 
  } 
}  

Output:

Hello

56. What is a parameterized constructor in Java?

When we create a constructor with several parameters, it is called a parameterized constructor. It allows you to assign different values to distinct objects. 

Example:

class Demo

{ 
    int id; 
    String name; 
    Demo(int i,String n)

    { 
      id = i; 
      name = n; 
    } 
    void display()
    {

       System.out.println(id+" "+name);

    }  
    public static void main(String args[])

    { 
        Demo s1 = new Demo(1,"Jac"); 
        Demo s2 = new Demo(2,"Samy"); 
        s1.display(); 
        s2.display(); 
  } 
}  

Output:

 

1 Jac
2 Samy

57. What is constructor overloading?

In Java, you can overload constructors, just like methods. You can create more than one constructor with a different parameter list to perform different tasks. The Java compiler calls the constructor depending upon the number of parameters and their data types.

Example:

class Demo

{ 
    int id; 
    String name; 
    Demo(int i,String n)

    { 
      id = i; 
      name = n; 
    } 
    Demo (int id)
    {
      id=i;
    }
    void display()
    {

      System.out.println(id+" "+name);

    } 
 
    public static void main(String args[])

    { 
      Demo s1 = new Demo(1,"Jacob"); 
      Demo s2 = new Demo(2); 
      s1.display(); 
      s2.display(); 
  } 
} 

Output:

1 Jacob
2 null

58. What is a copy constructor?

Java does not have a copy constructor, but you can copy the value of one object to another object, just like C++ copy constructor. You can use the following methods to copy one object’s value to another.

  • Using a constructor
  • Assigning an object’s value to another object
  • Using the clone() method of the object class

Example using constructor:

 

class Demo

{ 
    int id; 
    String name; 
    Demo(int i,String n)

    { 
      id = i; 
      name = n; 
    } 
    void display()
    {

       System.out.println(id+" "+name);

    } 
 
    public static void main(String args[])

    { 
      Demo s1 = new Demo(1,"Jacob"); 
      Demo s2 = new Demo(s1); 
      s1.display(); 
      s2.display(); 
  } 
}  

Output:

1 Jacob
1 Jacob

Conclusion

That’s it for our list of object-oriented programming questions and answers. OOP is an important part of programming and it’s required that you know it quite thoroughly. 

To program well, you must have an in-depth understanding of object-oriented features like classes, objects, abstraction, encapsulation, inheritance, polymorphism, and others. These OOPs interview questions should help with that. We have a guide for OOP concepts in Java if you need it.

Learn About Object-oriented Programming With These Courses

object-oriented programming courses

People Are Also Reading: 

 

 
By Ramya Shankar

A cheerful, full of life and vibrant person, I hold a lot of dreams that I want to fulfill on my own. My passion for writing started with small diary entries and travel blogs, after which I have moved on to writing well-researched technical content. I find it fascinating to blend thoughts and research and shape them into something beautiful through my writing.

View all post by the author

Subscribe to our Newsletter for Articles, News, & Jobs.

I accept the Terms and Conditions.
Thanks for subscribing! Look out for our welcome email to verify your email and get our free newsletters.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

Learn More

Please login to leave comments