[Easy-to-understand explanation! ] How to use Java encapsulation

1. Prior knowledge

-[Latest] How to build Java environment on Ubuntu

-[Even beginners can do it! ] How to create a Java environment on Windows 10 (JDK14.0.1)

-[Easy-to-understand explanation! ] How to use Java instance

-[Even beginners can do it! ] How to install Eclipse on Windows 10 (Java environment construction)

As prior knowledge, the contents of the above link are required.

2. What is encapsulation?

--Encapsulation is to define the attributes of an object and related operations together in the same class. --The attributes of the encapsulated class can only be accessed through the accessor method. --Other objects can't directly access the encapsulated class`, which prevents the attribute values from being inadvertently rewritten.

3. Basic writing

Test class


package package name;
public class main class name{
    public static void main(String[] args) {
        //Instance generation
Class name Variable name=new class name();
        //Put a value in setter
Variable name.set instance variable name(Actual argument);
        //Get the value entered by getter
        System.out.println(Variable name.getインスタンスVariable name());
    }
}

Encapsulation class



package package name;
class class name{
    //Definition of instance variables
private type name variable name;

    //Constructor (executed when instantiating)
name of the class(){
Initialization process, etc.
    }
    // setter
void set instance variable name(Type name Argument name){
        this.Variable name=Argument name;
    }
    // getter
Type name get instance variable name(){
return variable name;
    }
}

--Basic encapsulation is described as above.

4. Preparation

01.png

  1. Start Eclipse and select [File (F)]-> [New (N)]-> [Java Project]. 02.png
  2. Enter Test1 for the project name and click the Done button. 03.png
  3. Select [File (F)] → [New (N)] → [Class]. 05.png
  4. Enter Test1 for the package and name and click the Done button. 06.png
  5. Confirm that Test1.java has been created. 07.png Enter Test1 in the package, enter TestCapsule in the name, and click the Finish button, as in 6.3. 08.png
  6. Success if Test1.java and TestCapsule.java are created.

5. Description example

Test1.java


package Test1;
public class Test1 {
	public static void main(String[] args) {
        //Instance generation
		TestCapsule tc = new TestCapsule();
        //Put a value in setter
        tc.setHello("Good morning");
        //Get the value entered by getter
        System.out.println(tc.getHello());
    }
}

TestCapsule.java


package Test1;
public class TestCapsule {
	//Definition of instance variables
    private String hello;

    //Constructor (executed when instantiating)
	public TestCapsule() {
		this.hello = "Hello";
	}
    // setter
    public void setHello(String hello) {
		this.hello = hello;
	}
	// getter
    public String getHello() {
		return hello;
	}
}

--Copy the above sentence, specify S-JIS as the character code, save the file name as Test1.java, TestCapsule.java, and execute it. ↓ ↓ 09.png

6. Reasons for encapsulation

――The aim of encapsulation is to" protect data". --If you do not encapsulate, it will be easier to tamper with the data.

Example: A system that inputs the examinee's name and the examinee's score to make a pass / fail judgment

――A test with a maximum of 100 points passes 60 points or more. --Enter your name and score to determine if you pass or fail. --If you do not encapsulate when creating the above system, you can change the score unexpectedly as shown in the code below.

Test1.java


//A system that manages examinee names and examinee scores
package Test1;
public class Test1 {
	public static void main(String[] args) {
        //Instance generation
		TestCapsule tc1 = new TestCapsule("A",50);
		TestCapsule tc2 = new TestCapsule("B",60);

		//Unexpected variable changes
		tc1.score = 10000;
		tc2.score = -100;

		//Pass / fail display
		tc1.Result();
		tc2.Result();
    }
}

TestCapsule.java


package Test1;
public class TestCapsule {
	//Definition of instance variables
	String name;
	int score;

	//Constructor (executed when instantiating)
	public TestCapsule(String name, int score) {
		this.name = name;
		//Countermeasures against input of illegal points
		if(0 <= score && score <= 100) {
			//0 or more and 100 or less
			this.score = score;
		}else {
			//Less than 0 or more than 101
			this.score = 0;
		}
	}
	//Pass / fail judgment method
	void Result() {
		if(60 <= score) {
			//Pass
			System.out.println(name+"Is"+score+"Passed in terms of points.");
		}else {
			//failure
			System.out.println(name+"Is"+score+"It fails in terms of points.");
		}
	}
}

--Copy the above sentence, overwrite and save it in the Test1.java and TestCapsule.java created earlier, and execute it. ↓ ↓ 10.png

--In the above example, since the test is a perfect score of 100 points, neither 10000 points nor -100 points exist. --Encapsulation has the role ofpreventing unauthorized data manipulation by creating a situation where the function is passed once without directly manipulating the data. --If youencapsulate TestCapsule.java` in the above example, it will be as follows.

Test1.java


//A system that manages examinee names and examinee scores
package Test1;
public class Test1 {
	public static void main(String[] args) {
        //Instance generation
		TestCapsule tc1 = new TestCapsule("A",50);
		TestCapsule tc2 = new TestCapsule("B",60);

		//Unexpected variable changes
		tc1.setScore(10000);
		tc2.setScore(-100);

		//Pass / fail display
		tc1.Result();
		tc2.Result();

    }
}

TestCapsule.java


package Test1;
public class TestCapsule {
	//Definition of instance variables
	private String name;
	private int score;

	// setter
	public void setName(String name) {
		this.name = name;
	}
	// getter
	public String getName() {
		return name;
	}
	// setter
	public void setScore(int score) {
		//Countermeasures against input of illegal points
		if(0 <= score && score <= 100) {
			//0 or more and 100 or less
			this.score = score;
		}
	}
	// getter
	public int getScore() {
		return score;
	}

	//Constructor (executed when instantiating)
	public TestCapsule(String name, int score) {
		this.name = name;
		//Countermeasures against input of illegal points
		if(0 <= score && score <= 100) {
			//0 or more and 100 or less
			this.score = score;
		}else {
			//Less than 0 or more than 101
			this.score = 0;
		}
	}
	//Pass / fail judgment method
	void Result() {
		if(60 <= score) {
			//Pass
			System.out.println(name+"Is"+score+"Passed in terms of points.");
		}else {
			//failure
			System.out.println(name+"Is"+score+"It fails in terms of points.");
		}
	}
}

--Copy the above sentence, overwrite it with Test1.java, TestCapsule.java saved earlier, save it, and execute it. ↓ ↓ 11.png

7. Related

-[Useful to remember !!!] Easy creation of constructor and getter / setter in Eclipse -[Even beginners can do it! ] How to write Javadoc

Recommended Posts

[Easy-to-understand explanation! ] How to use Java encapsulation
[Easy-to-understand explanation! ] How to use Java polymorphism
[Easy-to-understand explanation! ] How to use ArrayList [Java]
[Easy-to-understand explanation! ] How to use Java overload
[Java] How to use Map
How to use java Optional
How to use java class
[Java] How to use string.format
How to use Java Map
How to use Java variables
[Java] How to use Optional ①
How to use Java HttpClient (Post)
[Java] How to use join method
[Processing × Java] How to use variables
[Java] How to use LinkedHashMap class
[JavaFX] [Java8] How to use GridPane
How to use class methods [Java]
[Java] How to use List [ArrayList]
How to use classes in Java?
[Processing × Java] How to use arrays
How to use Java lambda expressions
[Java] How to use Math class
How to use Java enum type
Multilingual Locale in Java How to use Locale
[Java] How to use the File class
[Java] How to use the hasNext function
How to use submit method (Java Silver)
[Java] How to use the HashMap class
[Java] How to use the toString () method
Studying how to use the constructor (java)
[Processing × Java] How to use the loop
How to use Java classes, definitions, import
[Java] [Maven3] Summary of how to use Maven3
[Processing × Java] How to use the class
[Processing × Java] How to use the function
[Java] How to use the Calendar class
[Java] Learn how to use Optional correctly
try-catch-finally exception handling How to use java
How to use Map
How to use with_option
How to use fields_for
How to use java.util.logging
How to use map
How to use collection_select
How to use Twitter4J
How to use active_hash! !!
How to use MapStruct
How to use TreeSet
[How to use label]
How to use hashes
How to use JUnit 5
How to use org.immutables
How to use java.util.stream.Collector
How to use VisualVM
[Java] How to use FileReader class and BufferedReader class
[Java] How to use Thread.sleep to pause the program
How to use Java framework with AWS Lambda! ??
How to use Java API with lambda expression
How to use the replace () method (Java Silver)
How to use Alibaba Cloud LOG Java Producer
[Java] How to use Calendar class and Date class