How to do call by reference in Java?

前端 未结 12 658
悲&欢浪女
悲&欢浪女 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:19

    Real pass-by-reference is impossible in Java. Java passes everything by value, including references. But you can simulate it with container Objects.

    Use any of these as a method parameter:

    • an array
    • a Collection
    • an AtomicXYZ class

    And if you change its contents in a method, the changed contents will be available to the calling context.


    Oops, you apparently mean calling a method by reference. This is also not possible in Java, as methods are no first-level citizens in Java. This may change in JDK 8, but for the time being, you will have to use interfaces to work around this limitation.

    public interface Foo{
        void doSomeThing();
    }
    
    public class SomeFoo implements Foo{
        public void doSomeThing(){
           System.out.println("foo");
        }
    }
    
    public class OtherFoo implements Foo{
        public void doSomeThing(){
           System.out.println("bar");
        }
    }
    

    Use Foo in your code, so you can easily substitute SomeFoo with OtherFoo.

提交回复
热议问题