Java implements all four key principles of object-oriented programming (OOP): encapsulation, inheritance, polymorphism, and abstraction.
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; } }
extends keyword. This promotes code reuse.public class Animal {} public class Dog extends Animal {}
Animal animal = new Dog(); animal.makeSound(); // will call the implementation in Dog
public interface Drawable { void draw(); }
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"
Story
In a bank project, a developer made all fields
publicand 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.