【问题标题】:Can I change object without using object reference as well as in non-static context?我可以在不使用对象引用的情况下以及在非静态上下文中更改对象吗?
【发布时间】:2018-05-03 21:05:10
【问题描述】:

在代码中,在main中调用有什么区别?

  • input.reverseArray(input);
  • reverseArray(input);
  • input = reverseArray(input);
  • input =input.reverseArray(input);

最后,如果 reverseArray 不是静态的,这些是否适用?


public class reverse
{
     
    public static void main(String args[])
    {
        int [] input = new int[]{4, 5, 8, 9, 10};      
    }
    public static void reverseArray(int inputArray[])
        {
            
             
            int temp;
             
            for (int i = 0; i < inputArray.length/2; i++) 
            {
                temp = inputArray[i];
                 
                inputArray[i] = inputArray[inputArray.length-1-i];
                 
                inputArray[inputArray.length-1-i] = temp;
            }
             
            
        }
}

【问题讨论】:

    标签: java function object methods


    【解决方案1】:
    • input.reverseArray(input); 无法编译,因为reverseArray 不是input 类型定义的方法,即int[]
    • reverseArray(input); 编译并正常工作。
    • input = reverseArray(input); 无法编译,因为 reverseArray 返回 void,因此无法将其分配给 input
    • input =input.reverseArray(input); 由于上述两个原因无法编译。

    如果reverseArray 不是静态的,那么以上都不会编译。特别是,reverseArray(input)静态方式静态上下文(即从static 方法)调用(不使用foo.reverseArray(input) 中的对象) ),但reverseArray 不是静态的。调用reverseArray的方法是使用reverse类型的对象,因为reverse类定义了reverseArray的方法:

    reverse myReverse = new reverse();
    myReverse.reverseArray(input);
    

    另请注意,根据 Java 约定,类应以 CamelCase 命名,因此您应将 reverse 更改为 Reverse

    【讨论】:

      猜你喜欢
      • 2016-10-03
      • 2015-09-15
      • 1970-01-01
      • 2010-09-21
      • 2015-02-01
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 2022-01-08
      相关资源
      最近更新 更多