Monday, January 20, 2025
HomeProgrammingWhat Is an Instance in Java?

What Is an Instance in Java?

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:

  1. Memory Allocation:
    • When an instance is created, memory is allocated for its fields (attributes) and methods.
  2. 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.
      
  3. 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
      
  4. 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
      

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.
RELATED ARTICLES

Banking Application in Java

Java PrintWriter Class

What Is CSS Hover?

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x