what is the difference between passing an object a

2019-08-09 04:13发布

I'm a little bit confused about the difference between passing an object and a primitive data as the parameter in Java. I read a post here explaining that when you pass a primitive data, you copy that data and pass it, but if you pass an object then you pass by the object reference. And I also read this discussion explaining that there's no pass-by-reference in Java. So what is the real difference between above two passes and why Java deals with them differently? Thanks in advance.

4条回答
Evening l夕情丶
2楼-- · 2019-08-09 04:52

When you pass a primitive, you actually pass a copy of value of that variable. This means changes done in the called method will not reflect in original variable.

When you pass an object you don't pass a copy, you pass a copy of 'handle' of that object by which you can access it and can change it. This 'handle' is a 'reference'. In this changes will be reflected in original.

Now one thing, what would happen when you pass array variable of a primitive type. In that case you do not pass a copy and the changes made will be reflected in original one.

查看更多
放荡不羁爱自由
3楼-- · 2019-08-09 04:59

There's no difference between passing a primitive and an object reference. Both are passed by value. In the first case, the primitive value is copied; in the second case, the reference value is copied.

查看更多
Rolldiameter
4楼-- · 2019-08-09 05:04

Just to clarify the responses so far

public class Car {

    private String type;

    public Car(String type) {
        this.type = type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public static void foo(Car someCar) {
        Car newCar = new Car("Sedan");//new object created
        someCar = newCar; //passed reference also points to newly created object
        someCar.setType("Coupe");//Referred object changes
        System.out.println(newCar.type);//Coupe
        System.out.println(someCar.type);//Coupe
    }

    public static void main(String[] args) {
        Car myCar = new Car("Sports");//new object created
        foo(myCar);//reference is passed by value
        System.out.println(myCar.type);//Sports
    }
}
查看更多
够拽才男人
5楼-- · 2019-08-09 05:10

To be clear, primitive types are passed by value, a copy of the type is what exists inside a function.

An Object is not copied, a reference to it is passed to the function. This means that you can change the Object within the function.

However, the reference is passed by value. When that posting creates a new Dog from within the function, the value of the reference changes. It is no longer a reference to the Dog that was passed to the function, but to a new one.

查看更多
登录 后发表回答