Junior — Middle
Can you explain the main ideas and principles of object-oriented programming?
sobes.tech AI
Answer from AI
Object-oriented programming (OOP) is based on several key principles:
- Encapsulation — combining data and methods that operate on that data into a single object, hiding internal implementation details from the outside world.
- Inheritance — a mechanism that allows creating new classes based on existing ones, inheriting their properties and behaviors.
- Polymorphism — the ability of objects of different classes to respond to the same messages (methods) in different ways.
- Abstraction — highlighting essential characteristics of an object while hiding non-essential details.
These principles help create flexible, extensible, and maintainable programs.
Example in Java:
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound(); // Outputs "Bark" — example of polymorphism
}
}