Junior
What is the difference between a class, an object, and an interface in Java?
sobes.tech AI
Answer from AI
A class is a blueprint for creating objects, defining their state (fields) and behavior (methods). An object (instance of a class) is a specific realization of the class in memory with a unique state. An interface is a contract, a fully abstract type that defines a set of methods that must be implemented by classes that implement it.
| Property | Class | Object | Interface |
|---|---|---|---|
| Entity | Template | Instance of a class | Contract |
| State | Can have fields (state) | Has specific field values | Fields are only static final |
| Behavior | Can have methods (behavior) | Executes methods defined by the class | Defines method signatures |
| Abstraction | Can be abstract | Not abstract | Fully abstract |
| Multiple inheritance | No | No | Yes (multiple implementation) |
| Creation | Created using the class keyword |
Created using the new keyword |
Created using the interface keyword |
Example:
// Class: template for creating cars
class Car {
String model; // Field (state)
// Method (behavior)
void start() {
System.out.println(model + " started.");
}
}
// Object: a specific car
Car myCar = new Car(); // Creating an object
myCar.model = "Toyota"; // Assigning state
myCar.start(); // Calling behavior
// Interface: contract for objects that can drive
interface Drivable {
void drive(); // Defines method signature
}
// Class implementing the interface
class Truck implements Drivable {
@Override
public void drive() {
System.out.println("Truck is driving.");
}
}
// Example of using the interface
Drivable vehicle = new Truck();
vehicle.drive();