π§βπ» What is a Class?
A class is a blueprint or template for creating objects.
It defines properties (variables) and behaviors (methods).
class Car {
String color; // property
void drive() { // method
System.out.println("The car is driving");
}
}ποΈ What is an Object?
An object is a real instance of a class.
You use the
newkeyword to create an object.
Car myCar = new Car();Example: Class + Object
class Animal {
String name;
void sound() {
System.out.println(name + " makes a sound.");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Animal(); // object created
a.name = "Dog"; // setting property
a.sound(); // calling method
}
}Dog makes a sound.π Why Use Classes and Objects?
Reuse code easily
Group related data and functions
Create multiple instances (objects) from one class
β Recap
Term | Meaning |
|---|---|
| Blueprint that defines variables & methods |
| Instance created from a class |
| Keyword used to create an object |