Encapsulation -- one of the three object-oriented features of java

Posted by gaza165 on Wed, 15 Dec 2021 19:12:10 +0100

1. Encapsulation (private)

It refers to hiding the properties and implementation details of objects, and only providing public access.
Benefits:
Hide implementation details and provide public access
It improves the reusability of the code
Improve security.
Packaging principle:
Hide all contents that do not need to be provided externally.
Hide properties and provide public methods to access them.
Introduction to private keyword in encapsulation:
1. It is a permission modifier.
2. Members can be modified (member variables and member methods)
3. Members modified by private can only be accessed in this class.
Exercise:
Randomly find a thing around you and define a class
Member variables are decorated with private and provide public getXxx() and setXxx() methods
And provide a show() method that can output all member variables
Then define a test class to create an object to use

class Person {
​    private String name;
​    private int age;
​    public void setName(String s) {
​        name = s;
​    }
​    public String getName() {
​        return name;
​    }
​    public void setAge(int i) {
​        age = i;
​    }
​    public int getAge() {
​        return age;
​    }
​    //Provides a method to print all member variables
​    public void show() {
​        //Member methods modified by private can only be accessed in this class
​        fun2();
​        System.out.println("full name:" + name + ",Age:" + age);
​    }
​    private void fun2() {
​        System.out.println("This is a private Decorated member method");
​    }
}
public class PrivateDemo1 {
​    public static void main(String[] args) {
​        //Create Person object
​        Person p1 = new Person();
​        //Because member variables are decorated with private keywords, they cannot be accessed in other classes.
//        p1.name;
//        p1.age;
​        //Only public methods can be called to get
​        String name = p1.getName();
​        int age = p1.getAge();
​        System.out.println(name + "---" + age);
​        //Assign values to member variables through public methods
​        p1.setName("Liu XX");
​        p1.setAge(18);
​        p1.show();
​        //Member methods modified by private are also inaccessible in other classes.
//        p1.fun2();
​    }
}

Introduction of this:
this: represents the object reference of the class
Remember:
this represents the object to which the method is called
Define member variables

​    private String name;
​    private int age;

Provide public getXxx() and setXxx() methods
Recall that when we named variables before, there was a rule: see the name to know the meaning
So let's change it
We changed the name of the formal parameter according to the meaning of the variable naming rule, but
After running the program, we found that although we also called the method and passed parameters, the result was still not successfully assigned
Why?
Because the calling of variables follows the principle of proximity
Ideally, we want the parameter passed in to be assigned to the member variable of the object
When the value of the actual uploaded argument is assigned later, it is assigned to the variable on the method, which has nothing to do with the member variable
The idea is to assign the passed in name value to the name value of the current object

​    public void setName(String name) { //"Jiang XX"
​        //Student3. We haven't introduced the way name is written

If there is one thing that can represent the object currently calling the method,
Who can replace the object of the current method?
java provides a keyword: this

       Student3.name = name;
​        //In so doing, it represents the parameters to be imported and assigns to the member variable name of the object currently calling the method.
​        this.name = name;
​    }
​    public String getName() {
​        //In fact, there is a this keyword hidden here, representing the member variable name that returns the object currently calling the method.
​        return this.name;
​    }
​    public void setAge(int age) {
​        this.age = age;
​    }
​    public int getAge() {
​        return age;    }
​    public void show() {
​        System.out.println("full name:" + name + ",Age:" + age);
​    }
}
public class StudentDemo2 {
​    public static void main(String[] args) {
​        //Create student objects and assign values to member variables
​        Student3 s1 = new Student3();
​        //Assign the name of the s1 object
​        s1.setName("ginger XX");
​        s1.setAge(18);
​        //Call the show() method to view the values of all member variables
​        s1.show();
​    }

Construction method:

The purpose of the constructor is to initialize the data in the object.
Format:
1. The method name is the same as the class name
2. There is no return value type, not even void
3. There is no specific return value

class Student {
​    private String name;
​    private int age;
​    Student(){
​        System.out.println("This is a parameterless construction method");
​    }
​    //getXxx() and setXxx() methods
​    public void setName(String name){
​        this.name = name;
​    }
​    public String getName(){
​        return name;
​    }
​    public void setAge(int age){
​        this.age = age;
​    }
​    public int getAge(){
​        return age;
​    }
​    public void show() {
​        System.out.println("full name:" + name + ",Age:" + age);
​    }
}
public class StructureDemo1 {

​    public static void main(String[] args) {

​        //create object

​        Student s = new Student();

//        s.show();

​    }

}

Some students began to think:
Before learning the construction method, we also came out of the new object. Now we know that we have always called a parameterless construction method internally. However, we have not written the construction method in the class, so the problem is where the construction method we have been using comes from?
Note:
1. If we do not give a construction method, the JVM will automatically provide us with a parameterless construction method.
2. If we give the construction method, the JVM will no longer provide the default parameterless construction method.
If we do not give a parameterless construction method, but give other parameterless construction methods, the JVM will no longer provide the default parameterless construction method. As long as we give the construction method, whether with or without parameters, the JVM will never provide the construction method without parameters.
3. Overloading can also occur in the same class. (the method name is the same, the parameter list is different, and it has nothing to do with the return value)
Function of construction method:
1. You can assign values to object member variables when creating objects
There are two ways to assign values to member variables of objects:
1) use the public setXxx() method provided by the class to assign values to member variables
2) assign a value to a private member variable using a construction method with parameters,
Note that when the variable name of the formal parameter is the same as that of the member variable, it needs to be used together with the this keyword

class Structure {
​    private String name;
​    private int age;
​    Structure() {
​        System.out.println("This is our own nonparametric construction method");
​    }
​    Structure(String name) {
​        System.out.println("This is our own tape name Parametric construction method with parameters");
​        this.name = name;
​    }
​    Structure(int age){
​        System.out.println("This is our own tape age Parametric construction method with parameters");
​        this.age = age;
​    }
​    Structure(String name,int age){
​        System.out.println("This is our own construction method with parameters with all member variables");
​        this.name = name;
​        this.age = age;
​    }
​    public void show() {
​        System.out.println("full name:" + name + ",Age:" + age);
​    }
}
public class StructureDemo2 {
​    public static void main(String[] args) {
​        Structure s1 = new Structure();
​        //Seeing the address value indicates that our object has been new
​        System.out.println(s1);
​        System.out.println("=======================");
​        //Create a second object
​        Structure s2 = new Structure("Lee XX");
​        s2.show(); //Li XX,0
​        System.out.println("=======================");
​        //Create a third object
​        Structure s3 = new Structure(17);
​        s3.show();//null,17
​        System.out.println("=======================");
​        //Create a fourth object
​        Structure s4 = new Structure("Zhang XX",18);
​        s4.show();
​    }
}

Execution order of object memory created by parameterless Construction:

Execution order of object memory created by structure with parameters:

Class composition:
Member variable
Construction method
Member method:
According to whether there is a return value:
1. Member method without return value
2. Member method with return value
According to whether there are parameters:
1. Member method without parameters
2. Member methods with parameters

 class Student2 {
​    private String name;
​    private int age;
​    //Nonparametric construction method
​    Student2() {
​    }
​    //Construction method of parameters containing all member variables
​    Student2(String name, int age) {
​        this.name = name;
​        this.age = age;
​    }
​    //Public getXxx() method and setXxx() method
​    public void setName(String name) {
​        this.name = name;
​    }
​    public String getName() {
​        return name;
​    }
​    public void setAge(int age) {
​        this.age = age;
​    }
​    public int getAge() {
​        return age;
​    }
​    //Member method with no parameters and no return value
​    public void printHello() {
​        System.out.println("HelloWorld");
​    }
​    //Member method with no parameter and return value
​    public String getTianQi() {
​        return "a sunny day";
​    }
​    //Member method with parameter and no return value
​    public void sum(int a, int b) {
​        System.out.println(a + b);
​    }
​    //Member method with parameter and return value
​    public String concat(String s1, String s2) {
​        return s1 + s2;
​    }
​    //Define a method to output all member variables
​    public void show() {
​        System.out.println("full name:" + name + ",Age:" + age);
​    }
}
public class StudentDemo {
​    public static void main(String[] args) {
​        //Create an object using a parameterless construction method
​        Student2 s1 = new Student2();
​        s1.show();
​        //Call a member method with no parameters and no return value
​        s1.printHello();
​        //Call a member method with no parameter and return value
​        String tianqi = s1.getTianQi();
​        System.out.println(tianqi);
​        //Call a member method with parameters and return values
​        String s = s1.concat("Digital plus Technology","yyds");
​        System.out.println(s);
​        //Calling a member method with parameters and no return value
​        s1.sum(12,45);
​       //Create objects using a construction method with parameters
​        Student2 s2 = new Student2("pottery",16);
​        s2.show();
​    }
}

static introduction:
Introduction: defines a person's class
After testing, it is found that when we give examples, we are all Chinese with the same nationality. We all have the same nationality. Each time we create, we will open up such a variable space in the heap memory, which is always a bit wasteful. Is there any way to let all people of the same nationality share the value of one nationality and have a common member variable for multiple objects when the value is the same
Java provides us with a keyword called static, which can modify member variables and member methods. When modifying member variables, multiple objects can share the value of a member variable.
The static member in the parent class can be regarded as a globally shared member

class Person{
​    //full name
​    private String name;
​    //Age
​    private int age;
​    //nationality
//    private String nationality;
​    private static String nationality;
​    public Person() {
​    }
​    public Person(String name, int age, String nationality) {
​        this.name = name;
​        this.age = age;
​        this.nationality = nationality;
​    }
​    public Person(String name, int age) {
​        this.name = name;
​        this.age = age;
​    }
​    public String getName() {
​        return name;
​    }
​    public void setName(String name) {
​        this.name = name;
​    }
​    public int getAge() {
​        return age;
​    }
​    public void setAge(int age) {
​        this.age = age;
​    }
​    public String getNationality() {
​        return nationality;
​    }
​    public void setNationality(String nationality) {
​        this.nationality = nationality;
​    }
​    public void show(){
​        System.out.println("full name:"+name+",Age:"+age+",Nationality:"+nationality);
​    }
}
public class PersonDemo {
​    public static void main(String[] args) {
​        //Create first object
​        Person p1 = new Person("Song Yi",26,"China");
​        p1.show();
​        //Create a second object
​        Person p2 = new Person("Hu Ge",30);
​        p2.show();
​        //Create a third object
​        Person p3 = new Person("Qian Xuesen",18);
​        p3.show();        System.out.println("=================================");
​        p1.setNationality("Russia");
​        p1.show();
​        p2.show();
​        p3.show();
​    }
}

Static memory diagram of static:

static features:
It can modify member variables and member methods
1. Load with class loading
Before running, the class file will be loaded into the method area, and the members modified by static will be loaded with the loading of the class, so the members modified by static will be stored in the method area.
Recall the main method
2. Prior to object existence
3. Shared by all objects of the class
For example: all Chinese have the same nationality information
When to use the static keyword?
If a member variable is shared by all objects, it should be defined as static.
Examples:
Hello bike: (can be modified by static)
Own water cup: (can't be modified by static)
4. Statically modified members can be called directly through the class name
Generally, when we develop in the future, we only need to see that there are static member variables or member methods in the class
In future calls, use class names. Static members are called in this way
It is recommended to call by class name, which is also the specification.
Different members are distinguished by calling
Therefore, statically modified members are generally called class members, which are related to classes

class Demo2{
​    //Define a non static member variable
​    int a = 10;
​    //Define a static member variable
​    static int b = 20;
}
public class StaticDemo1 {
​    public static void main(String[] args) {
//        Demo2 d1 = new Demo2();
//        System.out.println(d1.a);
//        System.out.println(d1.b);
​        System.out.println(Demo2.b);
​    }
}

Example standard class code version 3.0, a standard mobile phone class
Analysis:
Mobile:
Attributes: brand, color, price
Behavior: calling, texting, learning
Class:
Member variables: brand,color,price (decorated with private)
Construction method: nonparametric construction method and parametric construction method
Member methods: setXxx() and getXxx() methods
show(): output all member variables

public class Phone {
​    //Define member variables
​    private String brand;
​    private String color;
​    private int price;
​    //Define construction method
​    Phone() {
​    }
​    Phone(String brand, String color, int price) {
​        this.brand = brand;
​        this.color = color;
​        this.price = price;
​    }
​    //Define common setXxx() and getXxx()
​    public void setBrand(String brand) {
​        this.brand = brand;
​    }
​    public String getBrand() {
​        return brand;
​    }
​    public void setColor(String color) {
​        this.color = color;
​    }
​    public String getColor() {
​        return color;
​    }
​    public void setPrice(int price) {
​        this.price = price;
​    }
​    public int getPrice() {
​        return price;
​    }
​    //Define a method that can output all member variables
​    public void show() {
​        System.out.println("Brand:" + brand + ",Color:" + color + ",Price:" + price);
​    }
}
class PhoneDemo {
​    public static void main(String[] args) {
​        //Create an object using a parameterless constructor and assign a value to a member variable using setXxx()
​        System.out.println("=======Create an object using a parameterless construction method and use setXxx()Assign values to member variables=======");
​        Phone p1 = new Phone();
​        System.out.println("Before assignment:");
​        p1.show();
​        p1.setBrand("Huawei");
​        p1.setColor("black");
​        p1.setPrice(4999);
​        System.out.println("After assignment:");
​        p1.show();       System.out.println("======================================");
​        System.out.println("=======Create an object using a construction method with parameters, and use getXxx()Get member variable=======");
​        Phone p2 = new Phone("Smartisan Mobilephone","white",8888);
​        String brand = p2.getBrand();
​        String color = p2.getColor();
​        int price = p2.getPrice();
​        System.out.println("brand["+brand+"]\t colour["+color+"]\t Price["+price+"]");
​    }
}

Problems with static member access:
1. static can modify member variables and member methods
2. Non static member method:
1) non static member variables are accessed
Yes
2) static member variables are accessed
Yes
3) non static member methods are accessed
Yes
4) static member methods are accessed
Yes
Summary: non static member methods can access both static and non static members
Static member method:
1) non static member variables are accessed
No
2) static member variables are accessed
Yes
3) non static member methods are accessed
No
4) static member methods are accessed
Yes
Summary: static member methods can only access static members

class Demo3{
​    //Non static member variables
​    int a = 10;
​    //Static member variables
​    static int b = 20;
​    //Non static member method
​    public void fun1(){
​        System.out.println(a);
​        System.out.println(b);
​        fun2();
​        fun3();
​    }
​    public static void fun2(){
​        //Error:(47, 28) java: cannot reference non static variable a from static context
//        System.out.println(a);
//        System.out.println(b);
//        System.out.println("this is the static member method fun2");
​        //Error:(51, 9) java: cannot reference non static method fun3() from static context
//        fun3();
​        fun4();
​    }
​    public void fun3(){
​        System.out.println("This is a non static member method fun3");
​   }
​    public static void fun4(){
​        System.out.println("This is a static member method fun4");
​    }
}
public class StaticDemo2 {
​    public static void main(String[] args) {
​        Demo3 d = new Demo3();
//        d.fun1();
​        Demo3.fun2();
​        fun();
​    }
  public static void fun(){
​        System.out.println("helloworld");
​    }
}

Explain the purpose of code blocks: there will be relevant program questions during the interview in the future. You need to be familiar with the execution sequence of different code blocks.
Code block:
In Java, code enclosed with {} is called a code block
According to its location and declaration, it can be divided into
Local code block (treated as normal code)
Format: code that appears only in methods and is enclosed in braces is called a local code block
Benefits: release as soon as possible after use to improve memory utilization
Execution order: in a method, it is executed from top to bottom
Construct code block
It is defined outside the method in the class. Each time the construction method is called, the construction code block will be executed first, and then the construction method will be executed
Construction code block - construction method
If the new object in the main method also has local code blocks, the execution order is from top to bottom
Static code block
The code block modified by static is defined outside the method in the class
Execution sequence:
Static code block – construction code block – construction method
Once the static code block is executed once, the same program will not be executed again.
The static content belongs to the class itself. The program will be loaded only once from the beginning to the end, and will not be loaded repeatedly.
Synchronous code block (multi-threaded explanation).

class Demo {
​    //Nonparametric construction method
​    Demo() {
​       System.out.println("Demo Nonparametric construction method");
​    }
​    //Construct code block
​    {
​        int x = 200;
​        System.out.println(x);
​    }
​    //Static code block
​    static {
​        int w = 99;
​        System.out.println(w);
​    }
}
public class CodeDemo {
​    CodeDemo() {
​        int y = 400;
​       System.out.println(y);
​    }
​    {
​        int q = 500;
​        System.out.println(q);
​    }
​    static {
​        int r = 700;
​        System.out.println(r);
​    }
​   public static void main(String[] args) {
​        {
​            int a = 100;
​            System.out.println(a);
​        }
​        int a2 = 11;
​        System.out.println(a2);
​        {
​            int b = 200;
​            System.out.println(b);
​        }
​        System.out.println("============================");
        System.out.println(a);
//        Demo demo = new Demo();
//        Demo demo1 = new Demo();
​        Demo d = new Demo();
​        CodeDemo codeDemo = new CodeDemo();
​    }
}

Topics: Java Back-end OOP