Junior — Middle
How is object-oriented programming implemented in Java?
sobes.tech AI
Answer from AI
Object-oriented programming (OOP) in Java is implemented through core principles: encapsulation, inheritance, polymorphism, and abstraction.
- Classes and objects: A class is a template for creating objects, which are instances of the class.
- Encapsulation: Hiding data within a class using access modifiers (private, protected, public).
- Inheritance: Allows creating a new class based on an existing one, using the
extendskeyword. - Polymorphism: The ability to use objects of different classes through a common interface or base class.
- Abstraction: Defining abstract classes and interfaces to describe common properties and behaviors.
Example:
public class Animal {
public void sound() {
System.out.println("Some sound");
}
}
public class Dog extends Animal {
@Override
public void sound() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound(); // Outputs "Bark"
}
}