Basics
8.1 Introduction to OOP:
- Object-Oriented Programming (OOP) is a programming paradigm that focuses on organizing code into objects that represent real-world entities.
- It provides a way to structure and modularize code, making it more manageable and reusable.
8.2 Classes and Objects:
- In OOP, a class is a blueprint for creating objects.
- It defines the properties (attributes) and behaviors (methods) that objects of that class will have.
- An object is an instance of a class.
- Here's an example:
car.java file
public class CarRunner {
public static void main(String[] args) {
// Creating objects
Car car1 = new Car();
Car car2 = new Car();
// Accessing properties and invoking methods
car1.color = "Red";
car1.year = 2020;
car1.startEngine(); // Output: "Engine started!"
car2.color = "Blue";
car2.year = 2018;
car2.stopEngine(); // Output: "Engine stopped!"
}
}
CarRunner.java file
public class CarRunner {
public static void main(String[] args) {
// Creating objects
Car car1 = new Car();
Car car2 = new Car();
// Accessing properties and invoking methods
car1.color = "Red";
car1.year = 2020;
car1.startEngine(); // Output: "Engine started!"
car2.color = "Blue";
car2.year = 2018;
car2.stopEngine(); // Output: "Engine stopped!"
}
}
8.3 Encapsulation and Data Hiding:
- Encapsulation is the practice of hiding internal details of an object and providing public methods to interact with the object.