- Object-Oriented Programming (or OOP) is a JAVA paradigm that organizes software design around data, or objects rather than functions and logic.
Classes:
To create an object a Class
is required.
- A class is a blueprint for creating objects. It defines the properties and behaviors that objects of a certain class can have.
- Classes specify what data an object can have (attributes) and what it can do (methods).
- A class bundles its attributes and methods through encapsulation (1. Encapsulation), protecting the data.
public class Car {
// Fields, attributes, data variables -Â represent the data associated with a class. They define the state of an object.
String color;
String model;
int year;
// Methods, functions, data methods - define the behavior of a class.
// They operate on the fields of the class and perform actions or computations.
void displayDetails() {
System.out.println("Model: " + model + ", Color: " + color + ", Year: " + year);
}
}
Objects:
Objects are any real world entity (like car, bike, dog, ATM, etc.) which has two things:
- Properties or State
- Behavior or Function
Example
Dog is an object:
- Properties like: Age, Breed, Color, etc.
- Behaviors like: Bark, Sleep, Eat, etc.
An object is an instance of a class. Each object has its own set of fields defined by the class, but the methods are shared among all objects of the class.
Creating Objects
public class Main {
public static void main(String[] args) {
Car car1 = new Car(); // Creating an object of the Car class
car1.color = "Red"; // Setting fields
car1.model = "Toyota";
car1.year = 2020;
car1.displayDetails(); // Calling a method on the object
}
}