Introduction to Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a way of organizing code around objects. These objects combine data (called attributes) and behavior (called methods) that operate on the data.
Why Use OOP?
OOP offers several advantages:
- Modularity: Breaks programs into smaller, manageable parts (classes and objects).
- Reusability: Makes it easier to reuse existing code in new programs.
- Maintainability: Simplifies fixing bugs and making updates.
- Scalability: Allows for easy addition of new features.
Core Concepts of OOP
- Class: A blueprint or template for creating objects.
- Object: An instance of a class.
- Attributes: The properties or characteristics of an object (e.g.,
brand,speed). - Methods: The actions or behaviors of an object (e.g.,
start(),accelerate()).
Example: Car Class
Defining the Class
class Car {
// Attributes
String brand;
int speed;
// Methods
void start() {
System.out.println(brand + " is starting.");
}
void accelerate(int increment) { // Method
speed += increment;
System.out.println("New speed: " + speed);
}
}Attributes
Attributes define the properties of an object:
String brand;
int speed;Methods
Methods define the behavior of an object:
void start() {
System.out.println(brand + " is starting.");
}
void accelerate(int increment) {
speed += increment;
System.out.println("New speed: " + speed);
}Creating Objects
An object is an instance of a class. To create an object, we use the new keyword followed by a call to a constructor of the class.
Car car1 = new Car(); // Object creation
car1.start(); // Using an object to call a methodThis creates a new Car object with the specified brand, model, and year.
Accessing Object Members
We can access the fields and methods of an object using the dot notation:
System.out.println(myCar.brand); // Outputs: Toyota
myCar.startEngine(); // Outputs: The Toyota Corolla is starting...