JavaRush/Courses/JAVA 25 SELF/Creating objects with new

Creating objects with new

Open

1. The new keyword

In Java, to create an object of any class, you use the new keyword. This “magical” word asks the JVM to allocate memory for a new object and invoke its constructor.

Analogy:
If a class is a car blueprint, then new is the factory that builds a real car from that blueprint.

Example

Person vasya = new Person();

What happens here:

  1. new Person() — a new object of type Person is created (the constructor is called).
  2. vasya — a variable that holds a reference to the created object.

What it looks like in memory

When you write Person vasya = new Person();, memory is allocated for the object's fields (for example, name and age), and the variable vasya contains the address of that area — a reference.

Attention:
If you forget to write new, the variable will just be a reference that points to nothing (null). Trying to access fields or methods of such an “empty” object will result in a NullPointerException.

2. Calling a constructor: how does it work?

A constructor is a special method that is called when an object is created and initializes its fields, preparing the instance for use.

Syntax

ClassName variableName = new ClassName(arguments);
  • If the class has a constructor with parameters, you must pass them.
  • If the constructor has no parameters (or it's the default one), the parentheses remain empty.

Example: constructor with parameters

public class Person {
    String name;
    int age;

    // Constructor with parameters
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

Create an object:

Person petya = new Person("Petya", 25);

The values "Petya" and 25 will go into the name and age fields of the new object.

Constructor without parameters

public Person() {
    this.name = "Unnamed";
    this.age = 0;
}

Now you can write:

Person mysteryMan = new Person(); // name="Unnamed", age=0

3. Working with an object: fields and methods

After creating an object, you can access its fields and methods using the dot operator (.):

petya.name = "Pyotr";
System.out.println(petya.name); // Pyotr

petya.sayHello();

If the class has a method:

public void sayHello() {
    System.out.println("Hi, my name is " + name + "!");
}

Then calling petya.sayHello(); will print: Hi, my name is Pyotr!

Example: full class

public class Person {
    String name;
    int age;

    public Person(String name, int age) { // constructor
        this.name = name;
        this.age = age;
    }

    public void sayHello() { // method
        System.out.println("Hi, my name is " + name + "!");
    }
}

Usage:

Person vasya = new Person("Vasya", 30);
vasya.sayHello(); // Hi, my name is Vasya!

4. Reference variables: what are they?

A variable of a class type in Java is a reference to an object in memory, not the object itself.

Demonstration

Person vasya = new Person("Vasya", 30);
Person anotherVasya = vasya;

Now both vasya and anotherVasya point to the same object in memory. If you change a field through one variable, it changes for the other as well:

anotherVasya.age = 31;
System.out.println(vasya.age); // 31

Important:
If you create two different objects, they are independent:

Person petya = new Person("Petya", 25);
Person masha = new Person("Masha", 22);

petya.age = 99;
System.out.println(masha.age); // 22 (did not change!)

5. Example: creating and using multiple objects

Let's add several objects to the application. Suppose we have a Person class, and in main we'll create several people and print their greetings.

Person class

public class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void sayHello() {
        System.out.println("Hi, my name is " + name + ", I am " + age + " years old!");
    }
}

Usage in main

public class Main {
    public static void main(String[] args) {
        Person vasya = new Person("Vasya", 25);
        Person petya = new Person("Petya", 27);

        vasya.sayHello(); // Hi, my name is Vasya, I am 25 years old!
        petya.sayHello(); // Hi, my name is Petya, I am 27 years old!

        // Demonstration of object independence:
        vasya.age = 100;
        vasya.sayHello(); // Hi, my name is Vasya, I am 100 years old!
        petya.sayHello(); // Hi, my name is Petya, I am 27 years old!
    }
}

Program output:

Hi, my name is Vasya, I am 25 years old!
Hi, my name is Petya, I am 27 years old!
Hi, my name is Vasya, I am 100 years old!
Hi, my name is Petya, I am 27 years old!

6. Common mistakes when creating objects

Error #1: Forgot to write new

Person vasya;
vasya.name = "Vasya"; // NullPointerException!

The variable vasya doesn't reference any object (null). You must create an object with new.

Error #2: Didn't pass parameters to the constructor

Person petya = new Person(); // Compilation error if there is no no-arg constructor

If the class only has a constructor with parameters, you must provide those parameters when creating the object.

Error #3: Thinking that the variable stores the object itself

Person a = new Person("Anya", 20);
Person b = a;
b.age = 99;
System.out.println(a.age); // 99, because a and b are references to the same object!

In Java, a variable of a class type is always a reference, not the object itself.

Error #4: Changing fields of one object while expecting another not to change

Person x = new Person("X", 1);
Person y = x;
x.age = 42;
System.out.println(y.age); // 42

If you need two independent objects — create them separately!

1
Task
JAVA 25 SELF,  14 level,  3 lecture
Locked
Your First Virtual Pet
Your First Virtual Pet
1
Task
JAVA 25 SELF,  14 level,  3 lecture
Locked
Arrival of a new resident to the digital shelter
Arrival of a new resident to the digital shelter
1
Task
JAVA 25 SELF,  14 level,  3 lecture
Locked
Placing cars in a virtual showroom
Placing cars in a virtual showroom
1
Task
JAVA 25 SELF,  14 level,  3 lecture
Locked
Library book inventory: new arrivals
Library book inventory: new arrivals
Комментарии
  • популярные
  • новые
  • старые
Для того, чтобы оставить комментарий Вы должны sign in
This page has no comments yet