为什么我不能在Java中的不同类的方法中创建类对象?

use*_*814 5 java methods constructor class

我在我的代码中尝试了一些东西并且它不起作用(编译时的错误是"本地变量fundo永远不会被读取").我做了一些改变并且它有效,但我想知道它为什么不起作用.

我有一个名为Setor的类,在我的代码中我试图在Vendedor类中创建该类的对象

这是我的第一个代码:

class Vendedor{

  void abreTeatro(int codigoCamarote, int capacidadeCamarote, int precoCamarote, int codigoFrente, 
              int capacidadeFrente, int precoFrente, int codigoMeio, int capacidadeMeio, int precoMeio, int codigoFundo,
              int capacidadeFundo, int precoFundo)
  {
     Setor camarote = new Setor(codigoCamarote, capacidadeCamarote, precoCamarote);
     Setor frente = new Setor(codigoFrente, capacidadeFrente, precoFrente);
     Setor meio = new Setor(codigoMeio, capacidadeMeio, precoMeio);
     Setor fundo = new Setor(codigoFundo, capacidadeFundo, precoFundo);  

  };
 }
Run Code Online (Sandbox Code Playgroud)

如果我在方法之外创建对象,它可以正常工作,如下所示:

class Vendedor{

  Setor camarote;
  Setor frente;
  Setor meio;
  Setor fundo;


  void abreTeatro(int codigoCamarote, int capacidadeCamarote, int precoCamarote, int codigoFrente, 
              int capacidadeFrente, int precoFrente, int codigoMeio, int capacidadeMeio, int precoMeio, int codigoFundo,
              int capacidadeFundo, int precoFundo)
  {
     camarote = new Setor(codigoCamarote, capacidadeCamarote, precoCamarote);
     frente = new Setor(codigoFrente, capacidadeFrente, precoFrente);
     meio = new Setor(codigoMeio, capacidadeMeio, precoMeio);
     fundo = new Setor(codigoFundo, capacidadeFundo, precoFundo);  

  };
 }
Run Code Online (Sandbox Code Playgroud)

这是Setor类:

public class Setor
{

  int _codigo;
  int _capacidade;
  int _preco;

  public Setor (int codigo, int capacidade, int preco){
  _codigo = codigo;
  _capacidade = capacidade;
  _preco = preco;

  System.out.println(_codigo + " " + _capacidade + " " + _preco);
  };
 }
Run Code Online (Sandbox Code Playgroud)

我想知道我的第一次尝试有什么问题.

另外,我可能会使用一些错误的术语.对不起,非常欢迎编辑!

Nat*_*hes 11

不同之处在于声明填充变量的位置.

你的第一个例子是创建局部变量.方法完成后,它们将超出范围.没有任何东西可以指代它们,它们最终会被垃圾收集.

在第二个示例中,您将设置实例变量(声明位于类名后的花括号内,而不是在方法或构造函数定义中),因此在方法调用完成后,对象会保持不变.

  • 而且,严格来说,第一个没有"错误".你的对象实际上正在被创建...事情是你没有对它们做任何事情(并且没有人可以对它们做任何事情,因为你没有从任何地方引用它们,除了构造函数局部变量,它们一旦超出范围就会超出范围构造函数完成 - >您的对象未引用 - > GC进来并销毁它们) (3认同)
  • @Claudio:这是正确的,它只是没有做OP显然想要的. (2认同)
  • 为了我的学习目的,可以告诉他的代码中的构造函数在哪里? (2认同)
  • @Kick:哎呀,没有构造函数,我是幻觉.谢谢你,修好了. (2认同)
  • 哈,我分享了你的幻觉!我在哪里说构造函数==方法 (2认同)
  • @ Nathan Hughes,欢迎你.如果你能,你可以看看我的答案并投票给我吗?感谢你 (2认同)