Mastering the Java Interview Questions: OOPS Concepts and Code Examples

Introduction

Object-Oriented Programming (OOP) is a widely used programming paradigm that has been in existence for several decades. It is a programming methodology that is based on the concept of "objects" which are instances of classes that encapsulate data and methods to manipulate that data. OOP allows for the creation of reusable, modular, and scalable code. OOP is used in various programming languages like Java, Python, C++, etc. and it is important for developers to have a good understanding of OOP concepts to create efficient and effective code. In this blog, we will discuss some OOP interview questions that may be asked during interviews.

  1. What is OOP?

OOP stands for Object-Oriented Programming. It is a programming methodology that is based on the concept of "objects" which are instances of classes that encapsulate data and methods to manipulate that data. OOP allows for the creation of reusable, modular, and scalable code. OOP is used in various programming languages like Java, Python, C++, etc.

  1. What are the four fundamental principles of OOP?

The four fundamental principles of OOP are:

  1. Encapsulation
  2. Inheritance
  3. Polymorphism
  4. Abstraction

1. Encapsulation: Encapsulation is the process of hiding the internal details of an object from the outside world. It is achieved through the use of access modifiers like private, public, and protected. Encapsulation helps in maintaining the integrity of the data by preventing external entities from directly accessing or modifying the internal data of an object.

2. Inheritance: Inheritance is a mechanism that allows a class to inherit the properties and methods of another class. Inheritance helps in creating a hierarchy of classes where the properties and methods of a parent class can be reused by its child classes. This helps in creating modular and scalable code.

3. Polymorphism: Polymorphism is the ability of an object to take on different forms depending on the context in which it is used. Polymorphism can be achieved through method overloading and method overriding. Method overloading is when two or more methods have the same name but different parameters. Method overriding is when a subclass provides a specific implementation of a method that is already defined in its parent class.

4. Abstraction: Abstraction is the process of hiding the complexity of an object and exposing only the necessary details. Abstraction can be achieved through the use of abstract classes and interfaces. Abstract classes are classes that cannot be instantiated but can be inherited by other classes. Interfaces are similar to abstract classes but they only define the method signatures and do not provide any implementation.

  1. What is a class in JAVA?

A class in Java is a blueprint or a template for creating objects. It defines the properties and methods that an object of that class will have. A class can be thought of as a user-defined data type. It encapsulates the data and methods that are related to a particular entity. For example, if we want to create objects of a Car, we can define a Car class that will have properties like color, model, make, etc. and methods like start(), stop(), accelerate(), etc.

For example, let's say we have a class named Person:

java

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

In this example, the Person class has two properties, name and age, and a constructor that initializes those properties.

  1. What is an object in JAVA?

An object in Java is an instance of a class. It is created using the constructor of the class. An object has its own set of properties and methods that are defined in its class. For example, if we create an object of the Car class, we can set its properties like color, model, make, etc. and call its methods like start(), stop(), accelerate(), etc.

For example, we can create an instance of the Person class like this:

java
Person person = new Person("John", 30);

In this example, we create a Person object named person with the name "John" and age 30.

  1. What is a constructor in JAVA?

A constructor in Java is a special method that is used to create and initialize an object of a class. It has the same name as the class and does not have a return type. The constructor is called when an object of the class is created using the new keyword. The constructor is used to initialize the properties of the object to default values or to values provided by the user.

For example, let's say we have a class named Person with properties like name and age. We can create a constructor for the class like this:

java

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

In this example, the constructor takes two parameters, name and age, and assigns them to the corresponding properties of the object using the "this" keyword. When an object of the Person class is created using the new keyword, the constructor is called and the values of name and age are set for that object.

6. What is inheritance in JAVA?

Inheritance is a mechanism in OOP that allows a class to inherit the properties and methods of another class. Inheritance helps in creating a hierarchy of classes where the properties and methods of a parent class can be reused by its child classes. Inheritance helps in creating modular and scalable code.

For example, let's say we have a class named Vehicle with properties like color and model, and methods like start and stop. We can create a subclass named Car that inherits the properties and methods of the Vehicle class:


java
public class Vehicle {
    String color;
    
    public Vehicle(String color) {
        this.color = color;
    }
}

public class Car extends Vehicle {
    String model;
    
    public Car(String color, String model) {
        super(color);
        this.model = model;
    }
}

In this example, the Car class inherits the properties and methods of the Vehicle class. The Car class adds its own properties like acceleration and brake. When an object of the Car class is created, it can use the properties and methods of the Vehicle class as well as the properties and methods of the Car class.

7. What is an abstraction in JAVA?

Abstraction is a fundamental concept in object-oriented programming (OOP) that enables programmers to create complex systems by breaking them down into simpler, more manageable parts. Abstraction is the process of hiding the complexity of a system by focusing only on the essential features that are relevant to a particular context.

In OOP, abstraction is achieved through the use of abstract classes and interfaces. An abstract class is a class that cannot be instantiated and is designed to be subclassed by other classes. Abstract classes define one or more abstract methods, which are declared but not implemented. Subclasses of an abstract class are required to implement these abstract methods, providing concrete implementations that are specific to the subclass.

An interface is a collection of abstract methods that can be implemented by any class that implements the interface. Like abstract classes, interfaces define a set of methods that a class must implement to be considered a valid implementation of the interface.

The purpose of abstraction is to simplify the process of designing and building complex systems. By focusing on the essential features of a system and abstracting away the details that are not relevant to a particular context, programmers can create modular, reusable components that can be combined to create more complex systems.

8. What is an abstract class in JAVA?

An abstract class is a class that cannot be instantiated but can be subclassed. An abstract class is used to provide a common interface for its subclasses. An abstract class can have both abstract and non-abstract methods. Abstract methods are methods that do not have an implementation in the abstract class and must be implemented in the subclasses.

For example, let's say we have an abstract class named Shape with an abstract method named draw. We can create subclasses like Circle, Square, and Triangle that implement the draw method:

java
public abstract class Shape {
    public abstract void draw();
}

public class Circle extends Shape {
    @Override
    public void draw() {
        System.out.println("Drawing circle");
    }
}

public class Square extends Shape {
    @Override
    public void draw() {
        System.out.println("Drawing square");
    }
}

public class Triangle extends Shape {
    @Override
    public void draw() {
        System.out.println("Drawing triangle");
    }
}

In this example, the Shape class is an abstract class with an abstract method named draw. The subclasses Circle, Square, and Triangle implement the draw method to provide a specific implementation for each shape.

9. What is an interface in JAVA?

An interface is a collection of abstract methods that can be implemented by a class. An interface defines a contract that a class must follow to implement its methods. An interface can also contain constants and default methods. A class can implement multiple interfaces.

Here's an example of an interface:

java
public interface Drawable
    public void draw()
}

In this example, the Drawable interface defines a single method, draw(), which has no implementation. Any class that implements the Drawable interface must provide a concrete implementation of the draw() method.

Here's an example of a class that implements the Drawable interface:

java
public class Rectangle implements Drawable
    private int width; 
    private int height; 
    public Rectangle(int width, int height)
        this.width = width; 
        this.height = height; 
     } 
    public void draw()
     System.out.println("Drawing a rectangle with width " + width + " and height " + height); 
     } 
}

In this example, the Rectangle class implements the Drawable interface by providing a concrete implementation of the draw() method. The Rectangle class also has its own instance variables, width and height, which are used to draw the rectangle.

10. What is the difference between an abstract class and an interface in JAVA?

The main difference between an abstract class and an interface in OOP is that an abstract class can have both abstract and non-abstract methods while an interface can only have abstract methods. An abstract class can also have instance variables while an interface cannot. A class can only extend one abstract class while it can implement multiple interfaces.

11. What is encapsulation in JAVA?

Encapsulation is the practice of hiding the implementation details of a class from other classes. Encapsulation is used to protect the integrity of the data stored in a class and to prevent unauthorized access to that data. In Java, encapsulation is achieved by declaring class properties as private and providing public methods to access and modify those properties.

For example, let's say we have a class named BankAccount:
    java
    public class BankAccount { private String accountNumber; private double balance; public BankAccount(String accountNumber, double balance) { this.accountNumber = accountNumber; this.balance = balance; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { if (amount <= balance) { balance -= amount; } } public double getBalance() { return balance; } }

    In this example, the accountNumber and balance properties are declared as private, which means they can only be accessed within the BankAccount class. The deposit and withdraw methods are declared as public, which means they can be accessed from outside the class. The getBalance method is also declared as public but only returns the balance property and does not allow modification of the balance.

12. What is polymorphism in JAVA?

Polymorphism is a mechanism in OOP that allows a variable, method, or object to take on different forms depending on the context in which it is used. Polymorphism is used to create code that is more flexible and reusable. In Java, polymorphism is achieved by using method overloading and method overriding.

For example, let's say we have a class named Shape with a draw method. We can create subclasses named Circle and Rectangle that override the draw method:

java
public class Animal { public void makeSound() { System.out.println("The animal makes a sound"); } } public class Dog extends Animal { @Override public void makeSound() { System.out.println("The dog barks"); } } public class Zookeeper { public void feed(Animal animal) { System.out.println("Feeding the animal"); } public void feed(Dog dog) { System.out.println("Feeding the dog"); } }

In this example, the Shape class has a draw method that prints "Drawing shape". The Circle and Rectangle classes override the draw method and print "Drawing circle" and "Drawing rectangle" respectively. We can create an array of Shape objects and call the draw method on each object, and depending on the type of the object, the appropriate draw method will be called:

java
public static void main(String[] args) { Shape[] shapes = new Shape[2]; shapes[0] = new Circle(); shapes[1] = new Rectangle(); for (Shape shape : shapes) { shape.draw(); } }

This code will output:

arduino
Drawing circle 
Drawing rectangle

13. What is an overloaded constructor in JAVA?

An overloaded constructor is a constructor with the same name as the class but with different parameters. An overloaded constructor is used to create objects with different initial values. In Java, a class can have multiple constructors with different parameters.

For example, let's say we have a class named Rectangle with two properties, length and width. We can create two constructors, one with two parameters and another with three parameters:

java
public class Rectangle { int length; int width; public Rectangle(int length, int width) { this.length = length; this.width = width; } public Rectangle(int length, int width, String color) { this.length = length; this.width = width; this.color = color; } }

In this example, we have two constructors for the Rectangle class. The first constructor takes two parameters, length, and width, and initializes the corresponding properties. The second constructor takes three parameters, length, width, and color, and initializes the corresponding properties.

14. What is method overloading in JAVA?

Method overloading is a mechanism in OOP that allows a class to have multiple methods with the same name but different parameters. Method overloading is used to provide different implementations of a method depending on the parameters passed to it. When a method is called, the compiler determines which method to call based on the number and types of arguments passed to it.

For example, let's say we have a class named MathUtils with a method named add. We can create multiple versions of the add method to handle different types of data like integers, doubles, and floats:

java
public class Calculator { public int add(int a, int b) { return a + b; } public int add(int a, int b, int c) { return a + b + c; } }

In this example, we have three versions of the add method that take different types of data as parameters. When the add method is called, the compiler determines which version of the method to call based on the types of arguments passed to it.

15. What is method overriding in JAVA?

Method overriding is a mechanism in OOP that allows a subclass to provide a specific implementation of a method that is already defined in its parent class. Method overriding is used to provide a more specialized implementation of a method in the subclass. When a method is called on an object of the subclass, the implementation of the method in the subclass is used instead of the implementation in the parent class.

For example, let's say we have a class named Animal with a method named makeSound. We can create a subclass named Cat that overrides the makeSound method to provide a specific implementation for cats:

java
public class Animal { public void speak() { System.out.println("Animal speaks"); } } public class Cat extends Animal { @Override public void speak() { System.out.println("Cat meows"); } }

In this example, the Cat class overrides the makeSound method of its parent class Animal to provide a specific implementation for cats. When the makeSound method is called on an object of the Cat class, the implementation in the Cat class is used instead of the implementation in the Animal class.

16. What is the difference between a superclass and a subclass in JAVA?

A superclass is a class that is being extended by another class, while a subclass is a class that is extending a superclass. A subclass inherits properties and methods from its superclass, but can also add its own properties and methods.

17. What is the difference between method overloading and method overriding in JAVA?

Method overloading is the practice of defining multiple methods with the same name but different parameter lists, while method overriding is the practice of defining a method in a subclass with the same name and parameter list as a method in its superclass. Method overloading is resolved at compile-time based on the number and types of arguments passed to the method, while method overriding is resolved at runtime based on the actual type of the object.

18. What is the difference between a private and a protected method in JAVA?


In OOP, private and protected are access modifiers used to restrict access to class members. Here's how they differ:

  • private: A private method can only be accessed within the class in which it is defined. It cannot be accessed outside the class, not even by subclasses.
  • protected: A protected method can be accessed within the class in which it is defined, as well as by subclasses that extend the class.

Here's an example to illustrate the difference:

java
public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } 
}

In this example, the Animal class has two methods: makeSound() and eat(). makeSound() is private, which means it can only be accessed within the Animal class. eat() is protected, which means it can be accessed within the Animal class as well as by subclasses that extend the Animal class.

The Cat class extends the Animal class and has its own method, makeCatSound(). This method attempts to call the makeSound() method of the Animal class, which results in a compile error because makeSound() is private and cannot be accessed outside the Animal class. However, the eat() method of the Animal the class can be called from the Cat class because it is protected and can be accessed by subclasses.

19. What is the difference between composition and inheritance in JAVA?

Composition is the practice of creating complex objects by combining simpler objects, while inheritance is the practice of creating new classes that are derived from existing classes. Composition allows for greater flexibility and modularity, as objects can be easily reused and combined in different ways. Inheritance can lead to tight coupling between classes and can make it difficult to change the behavior of a class hierarchy once it has been established.

20. What is the difference between a class and an object in JAVA?

A class is a blueprint for creating objects, while an object is an instance of a class. A class defines the properties and behavior of a set of objects, while an object has a state (defined by its properties) and behavior (defined by its methods).

21. What is the difference between a constructor and a method in JAVA?

A constructor is a special method that is used to initialize an object when it is created, while a method is a function that is defined within a class and is used to perform some operation on an object. Constructors have the same name as the class and do not have a return type, while methods have a return type (which may be void) and can have any name.

22. What is the difference between a static method and an instance method in JAVA?

1. Static Method

A static method is a method that belongs to a class rather than to an instance of that class. This means that a static method can be called on the class itself, rather than on an object created from the class.

One common use case for a static method is to perform a utility function that doesn't require any instance-specific information. For example, a Math class might define static methods like sin(), cos(), and tan(), which can be used to perform trigonometric calculations without creating a Math object.

Here's an example of a static method:

java
public class Example
public static void printMessage(String message) {
    System.out.println(message); } 
// Call the static method Example.printMessage("Hello, world!");

In this example, the printMessage method is declared as static. This means that it can be called on the Example class itself, rather than on an Example object. The static method simply prints a message to the console. To call the static method, we use the syntax ClassName.methodName().

  • It's worth noting that static methods can't access instance variables or instance methods of the class.
  • They can only access other static variables or methods.
  • Also, because static methods belong to the class itself and not to any particular object, they can't be overridden in subclasses.

2. Instance Method

An instance method is a method that is associated with an instance of a class, and can access both instance variables and static variables and methods.

Here's an example:

java
public class Person { private String name; public Person(String name) { this.name = name; } public void sayHello() { System.out.println("Hello, my name is " + this.name); } } // Create a Person object and call the non-static method Person person = new Person("Alice"); person.sayHello();

In this example, the Person class defines a non-static method named sayHello(). This method uses the this keyword to access the name instance variable and print a message to the console. The method can only be called on a specific instance of the Person class, such as the person object created in the example.

  • Instance methods can access both instance variables and static variables of the class.
  • They can also call other non-static methods and static methods of the class.
  • Because non-static methods are associated with a specific instance of the class, they can be overridden in subclasses to provide different implementations.

23. What is the purpose of the "this" keyword in JAVA?

The "this" keyword is a reference to the current object. It is used to distinguish between instance variables and local variables with the same name, as well as to call other methods on the same object.

For example, let's say we have a class named Person with an instance variable named name:

java
public class Person
    private String name; 
    public Person(String name)
        this.name = name; 
    
    public void printName()
        System.out.println(this.name); 
     
}

In this example, the constructor takes a String argument and assigns it to the name instance variable using the "this" keyword. The printName method also uses the "this" keyword to refer to the name instance variable.

Conclusion

These are just a few of the many possible OOP interview questions that you may encounter. It is important to have a strong understanding of the principles of object-oriented programming, as well as practical experience with implementing these principles in code. By studying these questions and practicing your coding skills, you can prepare yourself for success in any OOP interview.


Author
Vaneesh Behl
Passionately writing and working in Tech Space for more than a decade.

Comments

Popular posts from this blog

17 Best Demo Websites for Automation Testing Practice

Automation Practice: Automate Amazon like E-Commerce Website with Selenium

14 Best Selenium Practice Exercises for Automation Practice

Mastering Selenium Practice: Automating Web Tables with Demo Examples

Selenium IDE Tutorial: How to Automate Web Testing with Easy-to-Use Interface

Mastering Selenium WebDriver: 25+ Essential Commands for Effective Web Testing

Automate GoDaddy.com Features with Selenium WebDriver

Top 10 Websites for Interview Preparation: Features and Benefits for Job Seekers

Learn Selenium Wait Commands: Implicit, Explicit and Fluent Waits

Top 10 Highly Paid Indian CEOs in the USA