In Java, an instance refers to a specific object that is created from a class. A class acts as a blueprint, and when you create an object from this blueprint, that object is called an instance of the class. Each instance has its own unique copy of the class’s properties and methods, allowing it to operate independently of other instances.
Key Features of an Instance in Java:
- Memory Allocation:
- When an instance is created, memory is allocated for its fields (attributes) and methods.
- Instance-Specific Data:
- Each instance has its own set of data, separate from other instances. For example:
class Dog { String name; } Dog dog1 = new Dog(); dog1.name = "Buddy"; Dog dog2 = new Dog(); dog2.name = "Charlie"; // Each instance has its own "name" field.
- Each instance has its own set of data, separate from other instances. For example:
- Accessing Members:
- You can access instance variables and methods using the dot operator (
.
):Dog myDog = new Dog(); myDog.name = "Max"; // Accessing and modifying the 'name' field
- You can access instance variables and methods using the dot operator (
- Instances Are Created Using the
new
Keyword:- An instance is typically created using the
new
keyword, which invokes the class’s constructor.Dog dog = new Dog(); // Creates an instance of the Dog class
- An instance is typically created using the
Example Code
class Car {
String color;
int speed;
void displayInfo() {
System.out.println("Color: " + color + ", Speed: " + speed);
}
}
public class Main {
public static void main(String[] args) {
// Create instances of the Car class
Car car1 = new Car();
car1.color = "Red";
car1.speed = 120;
Car car2 = new Car();
car2.color = "Blue";
car2.speed = 150;
// Display information for each instance
car1.displayInfo(); // Output: Color: Red, Speed: 120
car2.displayInfo(); // Output: Color: Blue, Speed: 150
}
}
Key Points to Remember
- Instance vs. Class: A class is the definition, while an instance is a specific realization of that class.
- Multiple Instances: Multiple instances can be created from the same class, and each instance operates independently.
- Instance Variables and Methods: These are specific to an object and differ from static variables and methods, which are shared across all instances of a class.