0
public class Cart {

    private String id;  
    private List<RentedMovie> rentedMovies = new ArrayList<RentedMovie>();  
    private long totalRent; 
    private long cartItemsCount;

    public Cart(Cart sessionCart) {
        this.id = sessionCart.id;
        this.rentedMovies = sessionCart.rentedMovies;
        this.totalRent = sessionCart.totalRent;
        this.cartItemsCount = sessionCart.cartItemsCount;
    } 
    ..<Getters and setters of all private varibles>..
}

I am little bit confused with my constructor concepts in java. In the above sample code, I have declared one Cart constructor which is having argument as Cart (that can be referring to another Cart object). As we can see in the sample class, all the instance variables are private, how can I able to access the private variables of Cart class via reference sessionCart directly. Ideally I should not be able to.

Please help.

2 Answers2

2

private access modifier allows access to any code in the same class that contains the private member, regardless if the access is to a member of the current instance or a different instance.

This allows methods such as compareTo and clone, as well as copy constructors, to access private fields of a different instance of the same class.

Eran
  • 387,369
  • 54
  • 702
  • 768
2

The access scope does is not related to "which object accesses the value of what other object", but rather to "which code (from which class) accesses members (of objects) of a given class"

In your case, the constructor is able to access these variables directly because the class of the object passed to the constructor is the same. That means, it's the code from the class itself that accesses it. Based on this, private access is available. In other words, its the Cart class accessing private fields from the Cart class (the same way it would say this.id, for example).

And BTW, it's not just the constructor that has this privilege, any code inside the Cart class can do the same.

Check more information on this documentation page: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

ernest_k
  • 44,416
  • 5
  • 53
  • 99