What is Class in Java? - Objects and Classes in Java {Explained}
A class in Java is a blueprint or template that defines the properties (fields) and behaviors (methods) that its objects will have. It's one of the core building blocks of object-oriented programming in Java.
Defining a Class
class Car {
String brand;
int speed;
void accelerate() {
speed += 10;
System.out.println(brand + " is now going " + speed + " km/h");
}
}
What is an Object?
An object is an actual instance of a class, created using the new keyword. While a class simply describes what a car looks like, an object represents one real, specific car with its own data.
Car myCar = new Car();
myCar.brand = "Toyota";
myCar.accelerate(); // Toyota is now going 10 km/h
Fields and Methods
- Fields (also called instance variables) store the state or data of an object
- Methods define the behavior or actions an object can perform
- Each object created from a class has its own separate copy of the instance fields
Constructors
A constructor is a special method used to initialize an object when it's created. It shares the same name as the class and has no return type.
class Car {
String brand;
Car(String brand) {
this.brand = brand;
}
}
Car myCar = new Car("Honda");
Multiple Objects from One Class
A single class can be used to create as many objects as needed, each with independent data.
Car car1 = new Car("Toyota");
Car car2 = new Car("Ford");
Class vs Object
- A class is a logical template; an object is a physical instance created from it
- No memory is allocated when a class is defined, only when an object is created
- A class is defined once but can produce many independent objects
Thinking of a class as a blueprint and an object as the actual building constructed from it is the easiest way to keep this core OOP concept straight.
Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.