Home  >  Article  >  Java  >  Object creation

Object creation

PHPz
PHPzOriginal
2024-07-24 13:07:421154browse

Criação de objetos

How objects are created

  • The line Vehicle minivan = new Vehicle(); declares an object of type Vehicle.

  • The statement does two things:
    Declares a variable called minivan of class Vehicle.
    Creates a physical copy of the object and assigns the minivan a reference to it using the new operator.

  • The new operator dynamically allocates memory for an object and returns a reference to it.

  • The reference is, more or less, the address of the object in memory allocated by new.

  • The reference is then stored in a variable.

  • In Java, all objects of a class must be dynamically allocated.

  • The two steps of the instruction can be rewritten to show each step individually.

Vehicle minivan; // declare a reference to the object.
minivan = new Vehicle(); // allocates a Vehicle object.

  • The first line declares minivan as a reference to an object of type Vehicle.

  • minivan is a variable that can reference an object, but is not an object.

  • For now, minivan does not reference an object.

  • The next line creates a new Vehicle object and assigns the minivan a reference to it.

  • Now minivan is linked to an object.

Reference variables and assignment

  • Object reference variables act differently from primitive type variables in assignment operations.

  • In primitive type variables, the variable on the left receives a copy of the value of the variable on the right.

  • In object reference variables, the variable on the left references the same object as the variable on the right.

  • This may cause unexpected results.

  • Example:
    Vehicle car1 = new Vehicle();
    Vehicle car2 = car1;

  • car1 and car2 reference the same object.

  • Changes made through car1 or car2 affect the same object.

  • When:
    car1.mpg = 26;
    System.out.println(car1.mpg);
    System.out.println(car2.mpg);

  • There will be exit 26.

  • car1 and car2 reference the same object, but are not linked in other ways.

  • Subsequent assignments to car2 do not affect car1.

  • Example:
    Vehicle car1 = new Vehicle();
    Vehicle car2 = car1;
    Vehicle car3 = new Vehicle();
    car2 = car3;

  • car2 now references the same object as car3.

  • The object referenced by car1 remains unchanged.

The above is the detailed content of Object creation. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn