Can you explain the main principles of object-oriented programming in Java?
sobes.tech AI
Answer from AI
Main principles of object-oriented programming (OOP) in Java:
-
Encapsulation — combining data and methods that work with this data into a single class. Hiding internal implementation details and providing access through public methods (getters and setters).
-
Inheritance — the ability to create a new class based on an existing one, inheriting its properties and methods, which allows code reuse and the creation of class hierarchies.
-
Polymorphism — the ability of objects of different classes to respond to the same messages (methods) differently. In Java, this is achieved through method overriding and interfaces.
-
Abstraction — highlighting common characteristics and hiding implementation details. In Java, it is implemented through abstract classes and interfaces.
Example:
public abstract class Animal {
public abstract void sound();
}
public class Dog extends Animal {
@Override
public void sound() {
System.out.println("Bark");
}
}
public class Cat extends Animal {
@Override
public void sound() {
System.out.println("Meow");
}
}
This demonstrates inheritance (Dog and Cat inherit from Animal), abstraction (Animal is an abstract class), and polymorphism (different implementations of the sound method).