Encapsulation for reference variables?

This may be a general question, but I could not find anything good for him. I'm trying to figure encapsulation of reference variablesin Java.
In the code below:

class Special {
    private StringBuilder s = new StringBuilder("bob"); 
    StringBuilder getName() { return s; }
    void printName() { System.out.println(s); } 
}
public class TestSpecial {
    public static void main (String[] args ) {
    Special sp = new Special();
    StringBuilder s2 = sp.getName();
    s2.append("fred");
    sp.printName();
    }
}

Result: bobfred

At first I thought about creating our field privateand provided a method getter, this is a good encapsulation method. But when I looked at it in more detail, I saw that when I call getName(), I really return a copy, as always. But I do not return a copy of the object StringBuilder. I am returning a copy of the reference variable pointing to a single object StringBuilder. So, at the moment when it returns getName(), I have one object StringBuilderand two reference variables pointing to it (s and s2).

, ? :). .

+4
2

, .

-, . , , . String:

class Special {
    private String s = "bob"; 
    String getName() { return s; }
    void printName() { System.out.println(s); } 
}
public class TestSpecial {
    public static void main (String[] args ) {
        Special sp = new Special();
        String s2 = sp.getName();
        s2 += "fred";
        // Alternatively: StringBuilder s2 = new StringBuilder(sp.getName()).append("fred");
        sp.printName(); // prints "bob"
    }
}

. s StringBuilder, s.toString().

- , . , :

class Special {
    private StringBuilder s = new StringBuilder("bob"); 
    StringBuilder getName() { return new StringBuilder(s); } // return a copy of s
    void printName() { System.out.println(s); } 
}
public class TestSpecial {
    public static void main (String[] args ) {
        Special sp = new Special();
        StringBuilder s2 = sp.getName();
        s2.append("fred");
        sp.printName(); // prints "bob"
    }
}
+4

.

  • ( new StringBuilder(oldBuilder.toString())

     public class Student{
       private String name;
    
       public Student(Student s){
           this.name = s.name;
       }
    
    }
  • . copy Constructor .

    public Student implements Cloneable{
        private int rollNo;
        private String name;
        public Student clone(){
           Student s = (Student)super.clone();
           s.name = this.name;
           s.rollNo = this.rollNo;
           return s;
        }
    }

    
    public class Clazz{
        private Map students= new HashMap();
        public student getStudent(int rollNo){
          Student s = students.get(rollNo);
          return s.clone(); 
        }
    }
  • . Collections.unmodifiablecollection(). , , . , .

+1

Source: https://habr.com/ru/post/1629751/


All Articles