Junior
What principles of object-oriented programming exist?
sobes.tech AI
Answer from AI
- Encapsulation: Combining data and methods that operate on that data into a single object and hiding implementation details. Access to data is provided through public methods.
- Abstraction: Hiding complexity by representing essential characteristics of an object or system without including background details or explanations. Focuses on "what it does" rather than "how it does it".
- Inheritance: A mechanism that allows one class (child) to inherit properties and behaviors from another class (parent). Facilitates code reuse and the creation of class hierarchies.
- Polymorphism: The ability of objects of different classes to respond to the same message or method call in different ways, depending on their type. Allows uniform handling of objects from different classes.
Example of polymorphism:
class Animal {
public void sound() {
System.out.println("Generic animal sound");
}
}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Woof");
}
}
class Cat extends Animal {
@Override
public void sound() {
System.out.println("Meow");
}
}
// Using polymorphism
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.sound(); // Outputs "Woof"
myCat.sound(); // Outputs "Meow"