首页 > 解决方案 > 如何从对象访问元素?爪哇

问题描述

我是编程新手,目前是从 java 开始的。我想知道如何访问我创建的对象的元素。我以为我知道怎么做,但它似乎不起作用。我正在从一个方法而不是内部类中构造一个内部类内部的对象。我想知道您是否可以给我一些提示,为什么当我想访问刚刚创建的对象的值时它不起作用。我的意思是可以访问这些值,但它们应该不同于 0。就好像我的构造函数没有传回这些值一样。我确实将我的程序进行了调试,并且传递给构造函数的值是 0、2、2。谢谢。

public class puzzle{

       public class Build{

             int nb, piece, length;

             public Build(int nb, int piece, int length){
                   //In debug I see that the values are passed, but when I print in the method the values printed are all 0.
                   nb = nb;
                   piece = piece;
                   length = length;
}

}
   public void rectangle(String book){
   
         //line of code where I do manipulations

         Build box = new Build(beginning, tv, book.length());

        System.out.println(box.nb);  
        System.out.println(box.piece); //should print a value different then 0
        System.out.println(box.length); //should print a value different then 0


}

}

标签: javaobjectconstructor

解决方案


nb = nb;

这没有任何作用。它将 nb 设置为自身。

这里有 2 个完全不相关的变量。一个被称为int nb;并且是您Build班级的一个领域。另一个是方法参数,完全巧合也被命名为nb.

您要设置字段,使用参数值。

你有两个选择。

  1. 停止使用相同的名称。方法参数“优先”(在 java 中:Shadows the field)。

  2. 使用this.nbwhich 指的是字段:this.nb = nb;

第二种形式是惯用的java。去做。


推荐阅读