Access to private field without getter method?

Here is an excerpt from the JDK7 source code:

public String(String original) {
    this.value = original.value;
    this.hash = original.hash;
}

Both valueand hashis a field private. Why original.valuelegal?

+4
source share
6 answers

See in this table :

                   Access Levels
Modifier     | Class  | Package   |  Subclass | World
-------------+--------+-----------+-----------+--------
public       |   Y    |     Y     |     Y     |   Y
protected    |   Y    |     Y     |     Y     |   N
no modifier  |   Y    |     Y     |     N     |   N
private      |   Y  ← |     N     |     N     |   N    
+7
source

Access modifiers describe access for classes , not instances . Since it valuewas declared in a class String, all its elements, like constructors, have unlimited access to it.

+2
source

( , this).

+1
Both value and hash are private filed. Why is original.value legal?

String, .

+1

Modifier    Class   Package Subclass    World
---------------------------------------------

private     **Y**      N        N           N

http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

A private modifier indicates that an item can only be accessed in its class.

Since it is in the classroom, you can access it.

+1
source

Getters and seters are valid for implementation outside the scope of the class. Inside the class, you can get any variable without any restrictions.

0
source

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


All Articles