6

Java - can private marked fields always be changed in the main function?

 2 years ago
source link: https://www.codesd.com/item/java-can-private-marked-fields-always-be-changed-in-the-main-function.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Java - can private marked fields always be changed in the main function?

advertisements

So I'm new to Java, and learning access modifiers. I learned that if you declare a field private, you can only change and read it (from another classes) by using get and set methods. Is this not true for the parent class? Because it seems that it can still be changed in the main().

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final TextView txt = (TextView) findViewById(R.id.txt);
    Button btn = (Button) findViewById(R.id.btn);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Employee John = new Employee(01, "John", "Smith", 20000);
            John.salary = 20;
            txt.setText("ID : " + John.id + "\nName : " + John.name + "\nSalary : " + John.salary);

        }
    });
}

public class Employee{
    int id;
    String name;
    String last_name;
    private int salary;

    public Employee(int id, String name, String last_name, int salary) {
        this.id = id;
        this.name = name;
        this.last_name = last_name;
        this.salary = salary;
    }
}

}


There are 4 types of java access modifiers:

private
default //when no access modifier is specified
protected
public

Now let's understand the access modifiers by a simple table:

Basically access modifier determines if a data member, method, constructor or class can be accessed directly. They can still be modified no matter what access modifier you choose. For a better understanding I suggest you to go read about encapsulation. This will give you a good example of why access modifier exist.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK