Kuidas Java-s rakendatakse objektorienteeritud programmeerimise põhialuseid?
sobes.tech AI
Vastus AI-lt
In Java, the core 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. Typically, fields are madeprivate, and access is provided via getters and setters. -
Inheritance: implemented using the
extendskeyword. 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 treated uniformly through a common interface or base class.
-
Abstraction: implemented using abstract classes (
abstract class) and interfaces (interface), which define a common contract without concrete implementation.
Example:
public abstract class Animal {
public abstract void sound();
}
public class Dog extends Animal {
@Override
public void sound() {
System.out.println("Woof-woof");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
dog.sound(); // Polymorphism: calling the method of the specific class via the reference to the base class
}
}