Instantiate Objects
Creating an object in Java means using the new
keyword to instantiate a class.
Example:
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.
You can create as many objects as you need from the same class:
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.
Below is a full example putting it all together.
Key ideas:
Fields hold each carโs unique data.
Methods use that data.
Multiple cars can be made from the same blueprint.