in Java
1. Class and Object
Class: A blueprint for creating objects (a particular data structure), defining
fields (attributes) and methods (functions) that describe the behavior of the
objects.
Object: An instance of a class. It has its own unique state and can call
methods defined in the class.
Example:
class Car {
String model;
int year;
void start() {
System.out.println("The car is starting.");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.model = "Toyota";
myCar.year = 2020;
myCar.start();
}
}
, 2. Encapsulation
The process of wrapping data (variables) and code (methods) together as a
single unit.
It hides the internal state of the object from the outside world and only
allows access through public methods (getters and setters).
Access modifiers: private, protected, public.
Example:
class Account {
private double balance;
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public void withdraw(double amount) {
if (amount > 0 && balance >= amount) {
balance -= amount;
}
}
}
3. Inheritance
A mechanism where one class acquires the properties and behaviors
(methods) of another class.
It allows for code reuse and method overriding.
A class that inherits from another is called a subclass, and the class it
inherits from is the superclass.