Java - OOP - Basics

Object-Oriented Programming (OOP) is a programming paradigm that allows us to represent real-world objects in a program using classes and objects. It is based on the principles of encapsulation, inheritance, and polymorphism.

Advantages of OOP:

Modularity: OOP allows us to break a program into smaller modules, making it easier to understand, maintain, and modify.

Reusability: OOP promotes the reuse of code, reducing development time and effort.

Encapsulation: OOP allows us to hide the implementation details of a class from other classes, providing better security and maintainability.

Inheritance: OOP allows us to define a new class based on an existing class, inheriting its properties and methods.

Polymorphism: OOP allows us to use a single interface to represent different types of objects, making the code more flexible and extensible.

Basic terms related to OOP:

Class: A class is a blueprint or template for creating objects that define the properties and behaviors of an object.

Object: An object is an instance of a class that has its own state and behavior.

Inheritance: Inheritance is a mechanism that allows us to create a new class based on an existing class, inheriting its properties and methods.

Polymorphism: Polymorphism is the ability of an object to take on different forms, allowing us to use a single interface to represent different types of objects.

Encapsulation: Encapsulation is the process of hiding the implementation details of a class from other classes, providing better security and maintainability.

In Java, OOP is implemented using classes and objects. To create an object in Java, we first need to define a class. Here is an example of a simple class in Java:

public class Car {
   String make;
   String model;
   int year;
   public void start() {
      System.out.println("The car is starting");
   }
   public void stop() {
      System.out.println("The car is stopping");
   }
}

In this example, we have defined a class named "Car" that has three properties: "make", "model", and "year", and two methods: "start" and "stop". To create an object of this class, we can use the following code:

Car myCar = new Car();

This creates a new object of the "Car" class and assigns it to the variable "myCar". We can access the properties and methods of this object using the dot notation, like this:

myCar.make = "Honda";
myCar.model = "Civic";
myCar.year = 2022;
myCar.start();
myCar.stop();

This sets the values of the "make", "model", and "year" properties of the "myCar" object, and calls its "start" and "stop" methods.