What is Java Encapsulation?

What is encapsulation?

A function that restricts access to class fields and methods. It has the role of preventing fields and methods from being used for unexpected purposes.

//Example: User class with string name and integer money in the field
public class User {
	String name;
	int money;

	public User(String name, int money) {
		this.name = name;
		this.money = money;
	}
}

The name and money of the User class instance can be changed freely.

public class Main {
	public static void main(String[] args) {
		User user = new User("Taro Suzuki", 100);
		System.out.println(user.name + "The money you have" + user.money + "Circle");
//It can be a blank name
		user.name = "";
//The amount may be negative
		user.money = -1000;
		System.out.println(user.name + "The money you have" + user.money + "Circle");
	}
}

Execution result

Taro Suzuki's money is 100 yen
The money you have-1000 yen

Encapsulation method

Make the access modifiers of fields and methods private that you don't want other classes to change for encapsulation.

This will prevent it from being changed by other classes.

The standard is to make the field private and the method public.

//Example: Encapsulate User class
public class User {
	private String name;
	private int money;

	public User(String name, int money) {
		this.name = name;
		this.money = money;
	}
}

How to access private fields

If you make a field private, you will not be able to get or change the value of the field from other classes.

public class User {
//At this rate, the name of the instance,money cannot be changed
	private String name;
	private int money;

	public User(String name, int money) {
		this.name = name;
		this.money = money;
	}
}

In such a case, you can safely get and change the field value from outside the class by defining a method to get and change the field value in the class.

The method that gets the value of a field is called a getter, and the method that changes it is called a setter.

How to define a getter

The getter method name is generally something like "get field name". Returns the value of the field as the return value.

//Example: Add name and money getters to User class
public class User {
	private String name;
	private int money;

	public User(String name, int money) {
		this.name = name;
		this.money = money;
	}

//name getter
	public String getName() {
		return this.name;
	}

//money getter
	public int getMoney() {
		return this.money;
	}
}
//Get name and money using getter
public class Main {
	public static void main(String[] args) {
		User user = new User("Taro Suzuki", 100);
		System.out.println(user.getName() + "The money you have" + user.getMoney() + "Circle");
	}
}

Execution result

Taro Suzuki's money is 100 yen

How to define a setter

The setter method name is generally something like "set field name". Assign the value received as an argument to the value of the field.

//Example: Add name and money setters to User class
public class User {
	private String name;
	private int money;

	public User(String name, int money) {
		this.name = name;
		this.money = money;
	}

//name getter
	public String getName() {
		return this.name;
	}

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

//money getter
	public int getMoney() {
		return this.money;
	}

//money setter
	public void setMoney(int money) {
		this.money = money;
	}
}
public class Main {
	public static void main(String[] args) {
		User user = new User("Taro Suzuki", 100);
		System.out.println(user.getName() + "The money you have" + user.getMoney() + "Circle");
		user.setName("Taro Sato");
		user.setMoney(500);
		System.out.println(user.getName() + "The money you have" + user.getMoney() + "Circle");
	}
}

Execution result

Taro Suzuki's money is 100 yen
Taro Sato's money is 500 yen

Benefits of using getters and setters

If you use getters and setters, you can also get and change private fields, so isn't it the same as public? You may think, but using getters and setters has the following merits.

1. Fields can be read-only or write-only

If you define only getters for a field and you don't define a setter, the field will be read-only and you can use the value of the field while preventing it from being modified by other classes.

Also, if only the setter is defined for the field and the getter is not defined, the field will be write-only. (There is not much usage like this)

//Example: Disable money setter in User class to make money read-only
public class User {
	private String name;
	private int money;

	public User(String name, int money) {
		this.name = name;
		this.money = money;
	}

//name getter
	public String getName() {
		return this.name;
	}

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

//money getter
	public int getMoney() {
		return this.money;
	}

//Without a money setter
//Prevents money from being changed by other classes
//
//	public void setMoney(int money) {
//		this.money = money;
//	}
}

2. Renaming a field does not affect other classes

When renaming a field later, if you are not using getters or setters, you will need to modify the code for all classes that use the field.

However, if you are using getters and setters, you only need to modify the code in the getter and setter methods.

//Example: Even if the name of the User class is changed to userName, the main method does not need to be changed.
public class Main {
	public static void main(String[] args) {
		User user = new User("Taro Suzuki", 100);
		System.out.println(user.getName() + "The money you have" + user.getMoney() + "Circle");
		user.setName("Taro Sato");
		System.out.println(user.getName() + "The money you have" + user.getMoney() + "Circle");
	}
}
public class User {
	private String userName; //name ->Change to userName
	private int money;

	public User(String userName, int money) {
		this.userName = userName;
		this.money = money;
	}

//userName getter
	public String getName() {
		return this.userName;
	}

//userName setter
	public void setName(String userName) {
		this.userName = userName;
	}
//No need to change the code because the variable userName does not appear in the main method
public class Main {
	public static void main(String[] args) {
		User user = new User("Taro Suzuki", 100);
		System.out.println(user.getName() + "The money you have" + user.getMoney() + "Circle");
		user.setName("Taro Sato");
		System.out.println(user.getName() + "The money you have" + user.getMoney() + "Circle");
	}
}

Execution result

Taro Suzuki's money is 100 yen
Taro Sato's money is 100 yen

3. You can inspect the value before changing the value of the field

By adding code that checks the value of the argument in the setter's method, it is possible to prevent the value of the field from being changed to an unexpected value.

Example: Check for the correct number of characters before changing the userName of the User class

//userName setter
//Change userName if the argument string is 3 to 10 characters
	public void setName(String userName) {
		if (userName.length() < 3) {
			System.out.println("The name is too short");
		} else if (userName.length() > 11) {
			System.out.println("The name is too long");
		} else {
			this.userName = userName;
			System.out.println("Name"" + this.userName + "Changed to");
		}
	}
public class Main {
	public static void main(String[] args) {
		User user = new User("Taro Suzuki", 100);
		System.out.println(user.getName() + "The money you have" + user.getMoney() + "Circle");
		user.setName("Suzuki");
		user.setName("My name is Taro Suzuki! !!");
		user.setName("Taro Sato");
		System.out.println(user.getName() + "The money you have" + user.getMoney() + "Circle");
	}
}

Execution result

Taro Suzuki's money is 100 yen
The name is too short
The name is too long
Changed the name to "Taro Sato"
Taro Sato's money is 100 yen

Summary

Recommended Posts

What is Java Encapsulation?
What is java
What is Java <>?
What is Java
What is Java technology?
What is Java API-java
[Java] What is flatMap?
[Java] What is JavaBeans?
[Java] What is ArrayList?
What is Java Assertion? Summary.
java (encapsulation)
What is a Java collection?
[Java] Encapsulation
[Java] What is jaee j2ee?
[Java] What is class inheritance?
[Java basics] What is Class?
What is java escape analysis?
What is JVM (Java Virtual Machine)?
[Java] What got caught in encapsulation
What is thread safe (with Java)
[Java] What is Concurrent Modification Exception?
What is a lambda expression (Java)
What is Cubby
What is Docker?
What is maven?
What is Jackson?
What is Docker
What is self
What is Jenkins
What is ArgumentMatcher?
What is IM-Juggling?
What is params
What is SLF4J?
What is Facade? ??
What is Gradle?
What is POJO
What is centOS
What is RubyGem?
What is programming?
What is before_action?
What is Docker
What is Byte?
What is Tomcat
What is a class in Java language (3 /?)
What is the best file reading (Java)
What is a class in Java language (1 /?)
What is Java and Development Environment (MAC)
What is a class in Java language (2 /?)
What is the main method in Java?
What is Maven Assembly?
What is `docker-compose up`?
What is a constructor?
What is vue cli
What is an interface?
What is the Java Servlet / JSP MVC model?
What is Ruby's self?
What is hard coding?
What is a stream
What is Ruby's attr_accessor?
What is permission denied?
What is instance control?