0
0
Javaprogramming~5 mins

Object creation in Java

Choose your learning style9 modes available
Introduction

We create objects to represent things or ideas in our program. Objects hold data and actions together, making code easier to understand and use.

When you want to represent a real-world thing like a car or a person in your program.
When you need to group related data and actions together.
When you want to create many similar items with different details.
When you want to organize your code better by using classes and objects.
Syntax
Java
ClassName objectName = new ClassName();

ClassName is the blueprint or template for the object.

new keyword creates a new object in memory.

Examples
This creates a new Car object named myCar.
Java
Car myCar = new Car();
This creates a new Person object named person1.
Java
Person person1 = new Person();
This creates a new Book object named book.
Java
Book book = new Book();
Sample Program

This program creates a Dog object named myDog. It sets the dog's name and age, then prints them.

Java
public class ObjectCreationExample {
    public static void main(String[] args) {
        // Create a new object of class Dog
        Dog myDog = new Dog();
        myDog.name = "Buddy";
        myDog.age = 3;

        System.out.println("Dog's name: " + myDog.name);
        System.out.println("Dog's age: " + myDog.age);
    }
}

class Dog {
    String name;
    int age;
}
OutputSuccess
Important Notes

You must create an object before you can use its data or actions.

The new keyword always creates a fresh object in memory.

Each object can have its own unique data.

Summary

Objects are created using the new keyword and a class name.

Objects hold data and actions together.

Creating objects helps organize and reuse code easily.