R
R
RomKing2020-12-22 10:22:58
Java
RomKing, 2020-12-22 10:22:58

Java: Why does a default object get assigned to a variable on its own?

Greetings. Tell me, please, Java experts. Below is an example of code in which I do not understand the assignment of object properties to a variable, namely, why does the object work as it should, despite the fact that carwe did not write the address of this object in the variable?

public class Human {
    String name;
    Car3 car;
    BankAccount1 bA;


void info () {
System.out.println(car.color);
    }
}

class Car3 {
    Car3(String c, String e) {
    color=c;
    engine=e;
}
    
    String color;
    String engine;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-01-10
@RomKing

Your code is poorly formatted, so it's not obvious:

public class Human {
    String name; // по-умолчанию все поля null
    Car3 car;


    void info() {
        // Компилятор ничего не знает о значении полей.
        // Он только знает, что есть поле car типа Car3
        // По тому он и позволяет его писать
        System.out.println(car.color);
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question