Java encapsulation private public

What is encapsulation?

Reference: Quoted from "Thorough Strategy Java SE 11 Silver Problem Collection":

Encapsulation is a "class for what" by combining related data and the processing that requires that data into one when dividing software, and excluding irrelevant and irrelevant ones from the class. It is done to clarify the purpose of the class "Is it?", And aims at a state where there is no duplicate data or processing in other classes.

Modifier If private is set, it will not be possible to access from outside the class (possible within the class) Private state Can be accessed from outside the public class

When the value entered by the user is 0 to 10, assign it to the private variable num and display it.

class Number {
  private int num;//Make it inaccessible from the outside

  public void setNum(int n){
    if(n >= 0&&n <= 10){
       num = n;
    }else{
      system.out.println("The value entered is invalid.");
    }
  }
  public int getNum(){//
    return num; //Returns a return value
  }
}
import java.io.*;
class Sample {
  public static void main(String[] args) throws IOException{
    BufferedReader br = new BufferedReader(new inputstreamreader(system.in))
    String str = br.readLine();//I will assume that you have entered 8.
    n = Integer.parseInt(str);
    Number nb1 = new Number();  
    //Such access is not possible
    //nb1.num = 8;
    nb1.setNum(n);
    system.out.println("The entered value is"+nb1.getNum()+"is.");
  }
}

By using the public method in the same class to update the private variable, setting the conditional expression, and updating the variable only for the passed variable, it is possible to prevent the update of the wrong value.

Recommended Posts

Java encapsulation private public
java (encapsulation)
[Java] Encapsulation
About private public
About private public
private, protected, private permissions-java
Java encapsulation private public
Java paid private memo
What is Java Encapsulation?
Check Java9 Interface private methods
Java encapsulation and getters and setters
Competitive programming private cheat sheet (Java)
[Java] What got caught in encapsulation
Java
Get the public URL of a private Flickr file in Java
Try to extract java public method
[Java] Test private methods with JUnit
Encapsulation
Java
Force non-instantiation with Effective Java private constructor
[Easy-to-understand explanation! ] How to use Java encapsulation