Junior
What is object-oriented programming (OOP) in Java?
sobes.tech AI
Answer from AI
Object-oriented programming in Java is a paradigm based on the concept of "objects" that contain data (properties) and methods (actions).
Main principles of OOP in Java:
- Encapsulation: Hiding data and methods inside an object, access only through defined interfaces. Ensures data security and modularity.
- Inheritance: Allows creating new classes (subclasses) based on existing ones (superclasses), inheriting their properties and methods. Promotes code reuse.
- Polymorphism: Enables using objects of different classes through a common interface. Provides flexibility and extensibility. Includes compile-time (overloading) and runtime (overriding) polymorphism.
- Abstraction: Highlighting essential characteristics and hiding non-essential details. Simplifies complex systems.
Example of a class in Java:
public class Car {
private String brand; // Encapsulated property
private String model;
private int year;
public Car(String brand, String model, int year) { // Constructor
this.brand = brand;
this.model = model;
this.year = year;
}
public void displayInfo() { // Method
System.out.println("Brand: " + brand + ", Model: " + model + ", Year: " + year);
}
// Getters and setters
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
}
Example of using OOP principles:
// Inheritance
public class ElectricCar extends Car {
private int batteryCapacity;
public ElectricCar(String brand, String model, int year, int batteryCapacity) {
super(brand, model, year); // Call parent constructor
this.batteryCapacity = batteryCapacity;
}
@Override // Polymorphism (method overriding)
public void displayInfo() {
super.displayInfo(); // Call parent method
System.out.println("Battery Capacity: " + batteryCapacity + " kWh");
}
}
// Using objects
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota", "Camry", 2020);
Car myElectricCar = new ElectricCar("Tesla", "Model 3", 2022, 75);
myCar.displayInfo();
myElectricCar.displayInfo(); // Polymorphism in action
}
}
Advantages of OOP:
- Code reuse: Through inheritance.
- Ease of maintenance: Changes affect only specific objects or classes.
- Flexibility and extensibility: Thanks to polymorphism.
- Improved code organization: Dividing system into modules (objects).
- Data security: Through encapsulation.