Classes and objects are fundamental concepts of Object-Oriented Programming (OOP) in Java. A class acts as a blueprint that defines the properties and behaviors of an entity, while an object is a real instance of that class created in memory.
Key Points: • A class defines the structure, attributes, and methods of an object. • An object is a runtime instance of a class with its own state and behavior. • Multiple objects can be created from a single class. • Classes help achieve abstraction and code reusability. • Objects interact with each other by invoking methods and accessing data.
Example: Consider a Car class. The class defines attributes such as color and model, and behaviors such as start() and stop(). Each actual car created from the class is an object.
Code Example:
class Car {
String color;
String model;
void start() {
System.out.println("Car Started");
}
}
public class Demo {
public static void main(String[] args) {
Car car1 = new Car();
car1.color = "Red";
car1.model = "Honda City";
car1.start();
}
}Real-World Analogy:
Class: • Blueprint of a house
Object: • Actual house built using that blueprint
Similarly:
Class: • Employee
Objects: • John, David, and Sarah as individual employees
Interview Tip: A concise interview answer is:
"A class is a blueprint that defines the properties and behaviors of an entity, whereas an object is an actual instance of that class created at runtime. A single class can be used to create multiple objects, each having its own state and behavior."