Classes and Objects in Java
1. What is a Class in Java?
A class in Java is a blueprint or template that defines the
attributes (fields/variables) and behaviors (methods) of
objects. It does not store actual data but acts as a template for
creating objects.
Key Features of a Class:
A class contains fields (variables) and methods (functions).
It is used to define the structure and behavior of objects.
A class does not occupy memory until an object is created.
Objects are created from a class using the new keyword.
2. What is an Object in Java?
An object is an instance of a class. It has state (data) and behavior
(methods).
When a class is defined, no memory is allocated until an object is
created.
Key Features of an Object:
Has state (data/variables).
Has behavior (methods).
Has an identity (unique memory location).
Syntax of a Class
class ClassName {
// Fields (Instance Variables)
DataType variable1;
DataType variable2;
// Constructor (Optional)
ClassName() {
// Initialization code
}
// Methods
void methodName() {
// Code
}
}
Syntax of a Creating Object
ClassName objectName = new ClassName();
Example of a Class and an Object
class Car { public class CarExample {
String brand; public static void main(String[] args) {
Car myCar = new Car();
int speed;
myCar.brand = "Tesla";
myCar.speed = 200;
void showDetails() {
System.out.println("Brand: " + brand); myCar.showDetails();
}
System.out.println("Speed: " + speed + " km/h"); }
}
}
Real-World Example
A Bank Account Class with Deposit and Withdraw Methods.
class BankAccount {
String accountHolder;
double balance;
BankAccount(String name, double initialBalance) {
accountHolder = name;
balance = initialBalance;
}
void deposit(double amount) {
balance += amount;
System.out.println("Deposited: $" + amount);
}
void withdraw(double amount) {
if (amount > balance) {
System.out.println("Insufficient funds!");
} else {
balance -= amount;
System.out.println("Withdrawn: $" + amount);
}
}
void display() {
System.out.println("Account Holder: " +
accountHolder);
System.out.println("Balance: $" + balance);
}
}
public class BankExample {
public static void main(String[] args) {
BankAccount account = new BankAccount("John Doe", 1000);
account.display();
account.deposit(500);
account.withdraw(200);
account.display();
}
}
Thank You…..