Class vs Object in Java: Key Differences
Q: What is the difference between a class and an object in Java?
- Java
- Junior level question
Explore all the latest Java interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Java interview for FREE!
In Java, a class is a blueprint or template for creating objects, while an object is an instance of a class. Here are some key differences between classes and objects:
- A class defines the properties and behaviors that objects of that class will have, but does not actually create any objects. To create an object of a class, you must first define a variable of that class type and then use the `new` keyword to instantiate the object.
- Objects are concrete entities that exist in memory and can be manipulated by a program. Each object has its own set of properties, or instance variables, which can be read and modified by the program.
- Classes are typically used to model concepts or entities in the problem domain, such as a car, a bank account, or a customer. Objects of a class can represent specific instances of that concept, such as a particular car, bank account, or customer.
- Classes can have static members, such as static methods and static variables, which are associated with the class itself rather than with any specific object. Static members can be accessed using the class name, rather than an object reference.
- Objects can have instance methods, which operate on the object's instance variables and may interact with other objects. Instance methods can only be called on an object of the corresponding class.
Here's an example to illustrate the difference between a class and an object:
public class Car { private String make; private String model; private int year; public Car(String make, String model, int year) { this.make = make; this.model = model; this.year = year; } public void startEngine() { System.out.println("Starting the " + make + " " + model + "..."); } } public class Example { public static void main(String[] args) { // create an object of the Car class Car myCar = new Car("Toyota", "Corolla", 2022); // call the startEngine() method on the object myCar.startEngine(); } }
In this example, we define a `Car` class that has three instance variables (`make`, `model`, and `year`) and one instance method (`startEngine()`). We then create an object of the `Car` class in the `main()` method using the `new` keyword and pass in the arguments `"Toyota"`, `"Corolla"`, and `2022` to the constructor. We store the reference to the new object in a variable named `myCar`.
Finally, we call the `startEngine()` method on the `myCar` object using the dot operator (`.`). This causes the message "Starting the Toyota Corolla..." to be printed to the console. Note that the `startEngine()` method has access to the `make` and `model` instance variables of the `myCar` object, which were set when the object was created.


