[JAVA] Encapsulation

Purpose of the capsule

By not exposing the field, we apologize for the field value that should not be changed so that it cannot be changed.

About access control

Access control level

name How to write in the program Scope of permission for access
private private Only in the same class as myself
package private Write nothing (default) Only the same package as myself
protected protected Child classes that belong to the same package as themselves or inherit from themselves
public public All classes

Access control for fields and methods

** (Thinking) ** Basically, private is often used for fields. Each time a method is created, the scope of application is considered.

Setting fields via methods

getter

** (How to use) **

public A type that returns a value get field name(){
  return this.Field name;//
}

(code)

private String name;

public String getName(){
   return this.name;//Returns the value of name for this class
}

** (Calling method) **

System.out.println(getName());

setter

** (How to use) **

public void set field name (data type of argument variable name to put argument){
  this.Field name = variable name to put the argument
}

(code)

private String name;

public void setName(String name){
   this.name = name
}

** (Calling method) **

Instance name.setName("Yoshihiko");

Benefits of using getter / setter

** Read Only Write Only field can be realized. ** ** → write Only for set only, Read Only for get only

** Easy to change field names ** → When renaming a field, if another class uses the field name directly, it will be necessary to modify the other class, but if get / set is used, it will be in your own class. All you have to do is modify the class name in get / set.

** You can check access to the field ** → (Example) If a value of 0 or less is assigned to the field called mp, an error will be forcibly generated with throw new IllegalArgumentException and the system will be terminated.

	public void setMp(int mp) {
		if (mp < 0) {
			throw new IllegalArgumentException("Set mp to 0 or more");
		}
		mp = this.mp;
	}

Access control for classes

Access control level

name How to write in the program Scope of permission for access
public public all
package private Write nothing (default) Only the same package as myself

Features of non-public classes

-The class name may be different from the source file name -Multiple classes may be declared in one source file

Recommended Posts

Encapsulation
java (encapsulation)
Encapsulation review
About encapsulation
[Java] Encapsulation
Encapsulation, polymorphism
What is Java Encapsulation?
Glossary: Accessor / Accessor Method, Encapsulation
About encapsulation and inheritance
Java encapsulation private public