Sobes.tech
Junior — Middle

How are the main principles of object-oriented programming implemented in Java?

sobes.tech AI

Answer from AI

In Java, the main principles of object-oriented programming (OOP) are implemented as follows:

  • Encapsulation: achieved through access modifiers (private, protected, public), which restrict access to class fields and methods. Usually, fields are made private, and access is provided via getters and setters.

  • Inheritance: implemented using the extends keyword. It allows creating a new class based on an existing one, inheriting its properties and methods.

  • Polymorphism: achieved through method overriding and the use of interfaces. It allows objects of different classes to be processed uniformly through a common interface or base class.

  • Abstraction: implemented using abstract classes (abstract class) and interfaces (interface), which define a common contract without specific implementation.

Example:

public abstract class Animal {
    public abstract void sound();
}

public class Dog extends Animal {
    @Override
    public void sound() {
        System.out.println("Woof");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal dog = new Dog();
        dog.sound(); // Polymorphism: calling the method of the specific class through a base class reference
    }
}
How are the main principles of object-oriented… - sobes.tech