Object Creation and Storage · Criação e Armazenamento de Objetos
| English | Português |
|---|---|
| constructor/kənˈstrʌktə/ | construtor |
| instantiation/ˌɪnstænʃɪˈeɪʃn/ | instanciação |
Making a new object
- To create an object, use the
newkeyword and a constructor 构造函数. Scanner sc = new Scanner(System.in);builds a fresh Scanner object.- Instantiation 实例化 is the act of creating an object from a class.
- The constructor sets up the object's starting state.
Criando um novo objeto
- Para criar um objeto, use a palavra-chave
newe um construtor 构造函数. Scanner sc = new Scanner(System.in);cria um novo objeto Scanner.- Instanciação 实例化 é o ato de criar um objeto a partir de uma classe.
- O construtor configura o estado inicial do objeto.
Constructor arguments
- A constructor can take arguments to configure the new object.
new Random(42)seeds a random generator;new String("hi")copies text.- The arguments match the constructor's parameters, by position and type.
- Different constructors (overloaded) let you build the same class different ways.
Argumentos do construtor
- Um construtor pode receber argumentos para configurar o novo objeto.
new Random(42)inicializa um gerador aleatório;new String("hi")copia texto.- Os argumentos correspondem aos parâmetros do construtor, por posição e tipo.
- Construtores diferentes (sobrecarregados) permitem construir a mesma classe de formas distintas.
Storing the reference
newreturns a reference to the object; store it in a variable of the right type.Scanner sc = new Scanner(System.in);—scnow refers to that object.- The object lives in memory;
scis just the label pointing at it. - Lose the reference (no variable holds it) and the object becomes unreachable.
Armazenando a referência
newretorna uma referência ao objeto; armazene-a em uma variável do tipo correto.Scanner sc = new Scanner(System.in);—scagora se refere a esse objeto.- O objeto vive na memória;
scé apenas o rótulo apontando para ele. - Perder a referência (nenhuma variável a segura) e o objeto torna-se inacessível.
Two variables, one object
- Assigning one object variable to another copies the reference, not the object.
Scanner sc2 = sc;— nowscandsc2point to the same Scanner.- A change through
sc2is visible throughsc— it's one object. - This reference-copy behavior is a defining feature (and trap) of objects.
Duas variáveis, um objeto
- Atribuir uma variável de objeto a outra copia a referência, não o objeto.
Scanner sc2 = sc;— agorascesc2apontam para o mesmo Scanner.- Uma mudança através de
sc2é visível através desc— é um único objeto. - Esse comportamento de cópia de referência é uma característica definidora (e armadilha) dos objetos.
new creates ONE object and hands back a reference to it. Assigning that variable to another (b = a;) copies the reference, so both names point to the same object — not a second copy. Contrast primitives (int y = x; copies the value). Forgetting this leads to "I changed b, why did a change too?" surprises.
new CRIA UM único objeto e devolve uma referência a ele. Atribuir essa variável a outra (b = a;) copia a referência, então ambos os nomes apontam para o mesmo objeto — não uma segunda cópia. Contraste com primitivos (int y = x; copia o valor). Esquecer isso leva a surpresas do tipo "Eu alterei b, por que a também mudou?"
Instantiation and aliasing:
Random r = new Random();→rrefers to a new Random object.Random r2 = r;→r2points at the same object (no new object made).- Both
randr2now share one generator's state.
Instanciação e aliasing:
Random r = new Random();→rse refere a um novo objeto Random.Random r2 = r;→r2aponta para o mesmo objeto (nenhum novo objeto criado).- Ambos
rer2agora compartilham o estado de um único gerador.
Create an object with new plus a constructor (instantiation): new Scanner(System.in). new returns a reference you store in a variable. Assigning one object variable to another copies the reference — both then refer to the same object (unlike primitives, which copy the value).
Crie um objeto com new mais um construtor (instanciação): new Scanner(System.in). new retorna uma referência que você armazena em uma variável. Atribuir uma variável de objeto a outra copia a referência — ambas então se referem ao mesmo objeto (ao contrário de primitivos, que copiam o valor).
new makes one object; = copies the reference · new cria um objeto; = copia a referência
r and r2 share one object; x and y are independent copies. · r e r2 compartilham um objeto; x e y são cópias independentes.
Which keyword creates a new object? · Qual palavra-chave cria um novo objeto?
new plus a constructor instantiates an object. · new mais um construtor instantia um objeto.
The special method called to build a new object is a ___ (one word). · O método especial chamado para construir um novo objeto é um ___ (uma palavra).
The constructor sets up the new object. · O construtor configura o novo objeto.
After Random r2 = r; how many Random objects exist? · Após Random r2 = r; quantos objetos Random existem?
Assigning copies the reference, not the object — still one object. · A atribuição copia a referência, não o objeto — continua sendo um objeto.
Assigning one object variable to another (b = a) makes a second, independent object. · Atribuir uma variável de objeto a outra (b = a) cria um segundo objeto independente.
It copies the reference — both point to the same object. · Ele copia a referência — ambos apontam para o mesmo objeto.
For primitives, int y = x; copies the value, so x and y are independent. · Para primitivos, int y = x; copia o valor, então x e y são independentes.
Primitives copy the value; objects copy the reference. · Primitivos copiam o valor; objetos copiam a referência.