How to understand anotherString.value.length in java source String class

When looking at the java source code, I don't understand it. value is the private attribute of the String class, so you can directly access the value attribute in this class,

But anotherString.value, how can the instance object access the private attribute? After research, the private access modifier is not well understood. In this class, the instance can also access the private attribute of this class.

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    
    
    /** The value is used for character storage. */
    private final char value[];
    ...
    ...
    public boolean equals(Object anObject) {
    
    
        if (this == anObject) {
    
    
            return true;
        }
        if (anObject instanceof String) {
    
    
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
    
    
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
    
    
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }
}

example verification

You can see that there is a private a attribute in class A, and in the test method of class A, the instance object of A can access the private a attribute

public class Test {
    
    
    static void main(String[] args) {
    
    
        A a1 = new A();
        B b1 = new A();
        a1.test(b1); // 3
    }
}

class B {
    
    

}

class A extends B {
    
    
  private String[] a = {
    
    "H", "E", "L"};

  public void test(B b) {
    
    
    A a = (A)b;
    System.out.println(a.a.length);
  }
}

Guess you like

Origin blog.csdn.net/mochenangel/article/details/118996353