How to do call by reference in Java?

前端 未结 12 748
悲&欢浪女
悲&欢浪女 2021-01-30 17:36

Since Java doesnt support pointers, How is it possible to call a function by reference in Java like we do in C and C++??

12条回答
  •  没有蜡笔的小新
    2021-01-30 18:12

    Yes, you can implement Call by Reference in another way by "Pass by Reference".

    • You should pass the reference object of a class created.
    • Then you can manipulate the object's data by member function (.), which will be reflected in original data.

    In below code the original data --> x is manipulated by passing the reference object.

    public class Method_Call {
    static int x=50;
    public void change(Method_Call obj) {
        obj.x = 100;
    }
    
    public static void main(String[] args) {
    
        Method_Call obj = new Method_Call();
        System.out.println(x);
        obj.change(obj);
        System.out.println(x);
    
    }
    

    }

    Output: 50 100

提交回复
热议问题