allthingsare๐Ÿ…ฟ๏ธ.com Books โฌ…๏ธ Back allthingsare

โ€œWhen you pass through the waters, I will be with you.โ€
[Isaiah 43:2]


Instantiate Objects


9.2.1 Creating an Object

Creating an object in Java means using the new keyword to instantiate a class.

Example:

java
Car myCar = new Car();
  • Car is the class type.

  • myCar is a reference variable โ€” it points to the new object.

  • new Car() calls the class constructor and allocates memory for the object.

Once created, you can:

  • Access fields: myCar.color = "Red";

  • Call methods: myCar.start();

Each object gets its own copy of the fields โ€” myCar and yourCar are separate cars, even if they come from the same Car class.


9.2.2 Using Multiple Objects

You can create as many objects as you need from the same class:

java
Car car1 = new Car(); car1.color = "Blue"; Car car2 = new Car(); car2.color = "Black"; System.out.println("Car1 color: " + car1.color); System.out.println("Car2 color: " + car2.color); car1.start(); car2.start();

Here:

  • car1 and car2 are different instances.

  • Each has its own color and speed.

  • Methods act on the specific object.

This is what makes OOP powerful โ€” one blueprint, many independent objects.


9.2.3 Mini Lab: Full Example

Below is a full example putting it all together.

java
public class Car { String color; int speed; void start() { System.out.println("The " + color + " car starts."); } void accelerate() { speed += 15; System.out.println("Speeding up! Current speed: " + speed + " km/h"); } public static void main(String[] args) { Car myCar = new Car(); myCar.color = "Red"; myCar.start(); myCar.accelerate(); myCar.accelerate(); Car yourCar = new Car(); yourCar.color = "White"; yourCar.start(); yourCar.accelerate(); } }

Key ideas:

  • Fields hold each carโ€™s unique data.

  • Methods use that data.

  • Multiple cars can be made from the same blueprint.