Class 05 and object 1_ encapsulation

Keywords: Java Back-end Class

1, Process oriented and object oriented

  • The programmer has changed from a process oriented executor to an object-oriented commander

2, Creation and use of classes and objects

  • Class definition

    • Modifier keyword class name{
          Properties and fields;
          method();
      }
      //For example, we create a Person class
      class Person{
          //Human characteristics
          public String name;//full name
          public String sex;//Gender
          public int age;
          //Human behavior
          public void eat(){
              System.out.println("Dry rice");
          }
          public void Learn(){
              System.out.println("study");
          }
          public void sleep(){
              System.out.println("sleep");
          }
      }
      /*
      0.The class shall be named in the way of large hump
      1.Here we use the keyword class to define a class named Person.
      2.Some basic characteristics of the owner of this class are name, gender and age.
      3.Some basic behaviors of the owner of this class are eating, studying and sleeping.
      4.The modifier public can only be used to define a class with the same file name (otherwise an error will be reported). For example, your file name is Person.java, which can be defined by public class Person
      */
      
  • Object creation and use

    • class Person{
          //Human characteristics
          public String name;//full name
          public String sex;//Gender
          public int age;
          //Human behavior
          public void eat(){
              System.out.println("Dry rice");
          }
          public void Learn(){
              System.out.println("study");
          }
          public void sleep(){
              System.out.println("sleep");
          }
      }
      public class test {
          
          public static void main(String[] args) {
              Person person=new Person();
              System.out.println(person.name);//null
              System.out.println(person.sex);//null
              System.out.println(person.age);//0
              person.eat();//Dry rice
              person.Learn();//study
              person.sleep();//sleep
      
          }
      }
      /*
      1.Instantiate an object through new
      2.Call the members of the class through person
      */
      

4, Property of one of the members of the class

  • Syntax format

    • Modifier data type property name=initialize value;
      
      Modifier 
      1.Common modifiers are: public protected default private
      2.Other modifiers: static,final
       data type
       Basic data types+reference type
       Attribute name
       It is an identifier and conforms to naming rules and specifications
      
  • example

    • public class Person{
          private int age=21;
          private String name="Wei";
      }
      
  • Classification of variables in java

    • one.Distinguish between member variables and local variables
      1.Outside the method, variables declared within the class are called member variables
      2.Variables declared inside a method body are called local variables
       two.
      1.Member variables: divided into instance variables(Not to static modification)Class variable(with static modification)two types
      2.Local variables: formal parameters, method local variables, and code block local variables
      
    • Insert the code slice here

5, Class

  • Definition of method

    • Modifier data type method name(){
          Code content;
      }
      
      class Person{
          //Human characteristics
          public String name;//full name
          public String sex;//Gender
          public int age;
          //Human behavior
          public void eat(){
              System.out.println("Dry rice");
          }
          public void Learn(){
              System.out.println("study");
          }
          public void sleep(){
              System.out.println("sleep");
          }
      }
      //Method is a behavior of this class
      

6, Class

  • Constructor is a special method of java, which is used to initialize member variables;

  • rule of grammar

    • 1. The method name must be the same as the class name.
    • 2. The constructor has no return value type declaration.
    • 3. There must be at least one construction method in each class (if it is not clearly defined, the system will automatically generate a parameterless construction).
  • Parameterless constructor: the system will generate it automatically. If you define a parameterless constructor and want to call a parameterless constructor, you need to rewrite a parameterless constructor to avoid program error.

  • Parametric constructor

  • class Person{
        public String name;//full name
        public String sex;//Gender
        public int age;
        public Person(String name,String sex,int age){
            this.name=name;
            this.sex=sex;
            this.age=age;
        }
        public Person(String name,String sex){
            this.name=name;
            this.sex=sex;
        }
        public Person(String name){
            this.name=name;
        }
        public Person(){
        }
    }
    public class test {
      public static void main(String[] args) {
    		Person person1=new Person();//Instantiate an object with a parameterless constructor
            System.out.println(person1.age);//0
            System.out.println(person1.name);//null
            System.out.println(person1.sex);//null
            //Call the parameterized constructor to instantiate the object
            Person person2=new Person("Wei","male",18);
            System.out.println(person2.age);//18
            System.out.println(person2.name);//Wei
            System.out.println(person2.sex);//male
        }
    }
    //The parameters of the constructor can be adjusted according to the parameters you want
    
  • this keyword

    • This indicates the current object reference (note that it is not the current object). You can use this to access the fields and methods of the object

    • this Three common methods of
      1.this.name=name;//Use this to reduce program ambiguity
      2.this.method();
      3.this("bit", 12, "man");//this calls the constructor
      class Person {
          private String name;//Instance member variable
          private int age;
          private String sex;
      //Default constructor construction object
      public Person() {
      	//this calls the constructor
      	this("bit", 12, "man");//It must be displayed on the first line
      }
      //The relationship between these two constructors is overloaded.
          public Person(String name,int age,String sex) {
          this.name = name;
          this.age = age;
          this.sex = sex;
      }
      public void show() {
      System.out.println("name: "+name+" age: "+age+" sex: "+sex);
      	}
      }
      public class Main{
      	public static void main(String[] args) {
              Person person = new Person();//Calling a constructor without parameters
              person.show();
      }
      

7, Encapsulation is one of the three features of class

  • Encapsulation, inheritance and polymorphism are the three important characteristics of class, and they are also the most important knowledge points of learning class.

  • encapsulation

    • definition
      • Abstract data types are used to encapsulate data and data-based operations to form an indivisible independent entity. The data is protected inside the abstract data type, the internal details are hidden as much as possible, and only some external interfaces are reserved to make it contact with the outside. The user does not need to know the internal details of the object, but can access the object through the interface provided by the object.
    • advantage
      • Reduce coupling: it can be developed, tested, optimized, used, understood and modified independently
      • Reduce the burden of maintenance: it can be more easily understood by programmers, and can not affect other modules during debugging
      • Effectively adjust performance: analyze and determine which modules affect the performance of the system
      • Improve software reusability
      • Reduces the risk of building large systems: even if the entire system is unavailable, these independent modules may be available
  • example

  • class Person{
        private String name;//full name
        private String sex;//Gender
        private int age;
    
        private String getName() {
            return name;
        }
        private String getSex() {
            return sex;
        }
        private int getAge() {
            return age;
        }
        public void print(){
            System.out.println("Grand Marshal"+getName()+" this year"+getAge()+" Gender"+getSex()+" Single ha ha");
        }
    
        public Person(String name, String sex, int age){
            this.name=name;
            this.sex=sex;
            this.age=age;
        }
    public static void main(String[] args) {
            Person person=new Person("rebel against the god","male",18);
            person.print();//Grand Marshal goes against the sky. This year, 18 gender men are single. Ha ha
        }
    //The Person class encapsulates the name, sex, age and other attributes. The outside world can only call the print() method, and cannot directly obtain the name attribute and sex attribute.
     
        
    
  • Example 2

    • class Person{
          private String name;//full name
          private String sex;//Gender
          private int age;
      
          public String getName() {
              return name;
          }
          public void setName(String name) {
              this.name = name;
          }
          public String getSex() {
              return sex;
          }
          public void setSex(String sex) {
              this.sex = sex;
          }
          public int getAge() {
              return age;
          }
          public void setAge(int age) {
              this.age = age;
          }
      
      }
      public static void main(String[] args) {
              Person person=new Person();
              person.setAge(19);
              person.setName("Wei");
              person.setSex("male");
              System.out.println(person.getAge());//19
              System.out.println(person.getName());//Wei
              System.out.println(person.getSex());//male
          }
      //Programs can manipulate properties through get and set
      

8, Keywords

  • static

    • Static variable: also known as class variable, that is, this variable belongs to a class. All instances of the class share a static variable, which can be accessed directly through the class name; Static variables exist only once in memory.

    • Instance variable: every time an instance is created, an instance variable will be generated, which will live and die with the instance.

    • example

      • class Persons {
            private int x;         // Instance variable
            private static int y;  // Static variable
            public static void main(String[] args) {
                Persons person = new Persons();
                int x = person.x;
                int y = Persons.y;
            }
        }
        1.use static Modified variables and methods can be directly through the class name.Variable and class name.Method to call
        2.Ordinary methods cannot be called static variable
        3.static Modified methods cannot call ordinary variables
        

9, Code block

  • Static variables and static statement blocks take precedence over instance variables and ordinary statement blocks. The initialization order of static variables and static statement blocks depends on their order in the code.

  • 1.	public static String staticField = "Static variable";
      
    2.  static {
        System.out.println("Static statement block");
    	}
      
    3.   public String field = "Instance variable";
     
    4.  {
        System.out.println("Common statement block");
    	}
    

Posted by FFFF on Sun, 31 Oct 2021 11:03:07 -0700