ProgrammingJava Developer

What are the main OOP principles used in Java and how are they implemented in practice?

Pass interviews with Hintsage AI assistant

Answer.

Java implements all four key principles of object-oriented programming (OOP): encapsulation, inheritance, polymorphism, and abstraction.

  • Encapsulation allows hiding the internal implementation of a class and providing access to data only through methods. Java uses access modifiers (private, protected, public) and getters/setters to achieve encapsulation.
public class Account { private double balance; public double getBalance() { return balance; } public void deposit(double amount) { this.balance += amount; } }
  • Inheritance allows creating a new class based on an existing one using the extends keyword. This promotes code reuse.
public class Animal {} public class Dog extends Animal {}
  • Polymorphism is manifested in the ability of one interface to serve multiple types. In Java, this is achieved through method overriding and interfaces.
Animal animal = new Dog(); animal.makeSound(); // will call the implementation in Dog
  • Abstraction is achieved by declaring abstract classes and interfaces, simplifying complex systems.
public interface Drawable { void draw(); }

Trick Question.

What happens if a Java class inherits both an interface and an abstract class that have methods with the same signature? What behavior will the derived class demonstrate?

Answer: If both the abstract class and the interface define the same method signature, then it is sufficient to implement that method once in the derived class. However, if the abstract class has implemented this method, Java will use its implementation. Interface default methods are overridden only as needed.

interface A { default void foo() { System.out.println("A"); }} abstract class B { void foo() { System.out.println("B"); }} class C extends B implements A {} // new C().foo() will output "B"

Examples of real errors due to lack of knowledge of the subtleties of the topic.


Story

In a bank project, a developer made all fields public and accessed them directly. This led to uncontrolled changes in the state of objects and made debugging hard. Subsequently, the entire code had to be rewritten to use private fields and access methods.


Story

One of the new employees tried to override a private method of a base class, believing it supports polymorphism. But in reality, a new method was created in the child class, and calls from the base class invoked the original version, leading to unexpected behavior.


Story

Using interfaces with default methods from multiple sources led to the error "class X inherits unrelated defaults for Y() from types A and B" — the employee did not know that such conflicts must be manually resolved in the child class.