Chapter IV Object-Oriented 2 (Notes)

Keywords: Java

Objects and References

  • Variable types in Java, except for the basic types, are referred to as reference types.

    • Basic types: byte, short, int, long, float, double, char, boolean;

    • Reference type: Array, String, Custom class;

  • Objects in Java operate on them by reference:

    • Example: Custom class Teacher(Teachers)
      
           class Teacher{           
                  String name;  
      ​
                  String prof;
      ​
                  String course;
       }
      Teacher dd = new Teacher();
       

The action of this statement (Teacher dd = new Teacher();) is often referred to as creating an object, which contains three actions.

  • "new Teacher()" is a template for a Teacher class that calls the constructor of the Teacher class to create a Teacher class object in heap space.

  • "Teacher dd" on the left creates a Teacher type reference variable. A reference to a Teacher class is an object reference that can be used later to point to a Teacher object.

  • The "=" operator causes the object reference to point to the Teacher object that was just created.

    This statement can be broken into two parts:

    Teacher dd;
    
    dd = new Teacher();

    There are two entities: one is the object reference variable, the other is the object itself.

    • new Teacher(); This statement creates entities in heap space, but we can't see or touch them. The object has no name and cannot be accessed directly. We need to access objects indirectly through object references. The object is like a balloon, but we can't catch it. A reference variable is like a rope that can be used to tie a balloon.

    • Teacher teacher1; // Create a rope, one that hasn't been tied to a balloon yet;

    • Teacher teacher2; // I made another rope and I haven't tied a balloon yet.

    • teacher1 = new Teacher();// Attach a balloon to teacher1;

    • teacher2 = teacher1 ;

      Copying occurs here, but the object is not copied, only the object reference is copied, teacher2 also points to the object teacher1 points to. The two ropes are tied to the same balloon.  

Value and Reference Passing

Actual Participation Parameters

  • Parameters: Parameters used when defining the name and body of a function to receive parameters passed in when the function is called.

  • Arguments: When a parameterized function is called, the parameters in parentheses after the function name are called "actual parameters". Arguments can be constants, variables, or expressions.

When passing parameters in a method call in Java, there are two kinds of parameter passing (all passing values, reference types passing object address values, and basic types passing specific values): the basic type passing the data value itself, and the reference type passing the reference to the object, not the object itself.

Value transfer: A copy of the actual parameters is passed to the function when the function is called so that modifications to the parameters in the function do not affect the actual parameters.

Case:

public class Demo1 { 
    /*       Basic type value transfer     */
    public static void main(String[] args) {
        Demo1 d = new Demo1();
        int a = 10;
        d.test(a);
        System.out.println(a);
    } 
    /*  
         The parameter b, which is directly assigned to B by the value of argument a, has two separate storage spaces in memory a,b  
    */  
    public void test(int b){
        b = 20;//A change in the value of b does not affect a
    }
}

Reference Pass: The address of the actual parameter is passed directly to the function when the function is called, and the modification to the parameter in the function will affect the actual parameter.

Case:

/*
   Reference type: When passed, the address value of the object is passed
 */
public static void main(String[] args) {
    Demo d = new Demo();
    Person zs = new Person("Zhang San", 20);
    d.test(zs);//Just passed the object's address to p
    System.out.println(zs.name);//Li Si
}
public void test(Person p){ //p and Z point to the same object
      p.name = "Li Si";
}

See a blogger's interpretation of value transfer and reference transfer image:

        You have a key to your home. When your friend wants to go to your home, if you give him your key directly, it's referencing. In this case, if he does anything with the key, such as carving his name on it, then when the key is returned to you, he will also carve his name on your own key.

        But if your friend wants to go to your house and you carve him a new key and you still have it in your own hands, that's value passing. In this case, what he does to the key will not affect the key in your hand.

this keyword

There are three uses: representing the current object, referencing member variables, and referencing member methods.

  • Within a class's method or construction method, member variable names can be referenced in a format such as "this.member variable name" to distinguish between member variables with the same name and local variables.

There are several points to note when using this to invoke a construction method:

  • this() can only be used in construction methods to call other construction methods, not member methods.

  • Statements that use this() to call a construction method in a construction method must be on the first line and can only occur once.

  • You cannot call each other using this() in two construction methods in a class.

Case:

public class Demo{   
    private int a;
    public Demo(int a){
    this.a = a;
    }
    public int getA(){
        return a;
    }
    public void setA(int a){
         this.a = a;
    }
}

static keyword

Statics are commonly used to modify the properties and methods of a class, such as modifying member variables, member methods, code blocks, internal classes, and so on.

  • static-modified content is loaded as the class is loaded (initialized when the class is loaded);

  • Decorated members, shared by all objects;

  • After adding static, only one copy is stored in the method area, and objects are no longer duplicated in the heap when they are created. Static attributes are shared by all objects of the class, that is, no matter how many objects are created, there is only one static attribute in memory.

  • Instead of creating an object, it is called directly by the class (through the class name). When modifying member methods, you can use the "class name. method name" method to avoid the tedious task of first new ing out the object. Public class Chinese {String name;//non-static attribute static String country; //static attribute

    Case:

public class Chinese {
     String name;// The name attribute is not recommended to be modified with static, which has only one part in memory and each object has a different name.
     int age;//Non-static members cannot be called by class name
     static String country = "China"; //Constants are generally modified to static  
​
    /*
       static Decoration methods, class methods, static methods cannot use non-static member variables, static resources load first with the class.
       Non-static loads as objects are created 
     */
    public static void test(){
        //System.out.println(name);
    }
​
    /*
       Non-static methods can use static variables, non-static methods must be called through objects, which load classes before they are created
     */
    public void test1(){
        System.out.println(country);
    }
}
public class Test {
public static void main(String[] args) {
    Chinese zs = new Chinese();
            zs.name = "Zhang San";
            zs.age = 20;

    Chinese ls = new Chinese();
    ls.name = "Li Si";
    ls.age = 20;

    Chinese.country = "china";
    System.out.println(zs.name);
    System.out.println(ls.name);
    System.out.println(zs.country);
    System.out.println(ls.country);

    Chinese.test(); //Static method, static variable recommend class name call
    }
}

Code block (code enclosed in {})

Code blocks are declared in classes, similar to a method body without a name, and are divided into instance blocks and static blocks.

  • Instance block: There may be many instance blocks in a class. The execution order of multiple instance blocks is from top to bottom. They are executed automatically after the object is created and before the construction method is called. They are executed once per object creation.

  • Static block: Initialized code block decorated with static that is executed only once (but can be executed multiple times at a time) when a class is loaded, multiple static executions in sequence, regardless of whether or not an object is created. Static {

    }

    Execute static method block before instance method block

    When does the class load?

    1. In which class is the main method executed and loaded;

(         2. When an object of a class is created;

        3. When calling a static property in a class, the method.

Case:

public class Demo {   
   String name;
   static String country = "China";
​
   public Demo(){
       System.out.println("Parametric construction");
   }
  {
      System.out.println("Instance Code Block");
  }
​
  static{
      System.out.println("Static Code Block 1");
  }
​
 static{
     System.out.println("Static Code Block 2");
  }
 }
public class TestDemo {
public static void main(String[] args) {
     new Demo();
     new Demo();
​
    //System.out.println(Demo.country);
   // System.out.println(Demo.country);
  }
}

Output results:

 

package

To better organize classes and avoid overwriting the same class name, JAVA provides a package mechanism to store all Java programs in their own directories, which are packages and packages can also be understood as a folder.

  • Effect:

    • Avoid class renames

    • Manage classes by function

    • Control access rights

The naming conventions for package s:

In a package name, you can use the.Sign to distinguish the level of the package (com.ffyc.javaOOP), which is typically lowercase.

Level 1: Types of projects, such as com (commercial), org (generally referred to as non-profit organizations), gov (government), edu, etc.

Level 2: Name of the company that the project is developed or run, e.g. oracle,sun,huawei, etc.

Level 3: The name of the project, such as bcms,oa,erp,cms, etc.

Level 4: Name of project module, e.g. bean,action,exception, etc.

  • Packages better manage logically related classes and control access between different packages

  • Class to import external packages, keyword "import"

Case:

//import imports the full class name of the class java.util.Date in another package (short for Date when using packages other than the current package)
import day2.Car;
​
import java.util.Date;
​
//import java.sql.Date;
public class Demo {
public static void main(String[] args) {
    new Date();
    new java.sql.Date(1000);//Only one computer can recognize the same class name, so to avoid duplicate class names, use a short name and a full name
    new Car();
​
   }
}

Access Permission Modifier

Access rights (large ->small): public,protected,default,private

Access modifier: Used to modify classes, member variables, member methods, internal classes, and control aligned access rights.

  • Public (public permissions, accessible by any class)

    Modifiers: classes, member variables, methods, internal classes

  • Protected (Protected permissions can be accessed by the same package class, if not by a subclass of that class.)

    Modifiers: member variables, methods, internal classes

  • Default (same package permissions, accessible only by classes in the same package)

    Modifiers: classes, member variables, methods, internal classes

  • Private (Private permissions, accessible only in your own class, not in other classes of the same package)

    Modifiers: member variables, methods, internal classes

The above modifiers are accessible in this class.

Private subclasses in the parent class are inaccessible, but protected subclasses are accessible.

Case:

public class Demo1 {public String pubname;
    protected String proname;
    String name;
    private String priname;
                    
    public void pubtest(){
        
    }
    protected void protest(){
​
    }
​
    void test(){
​
    }
​
    private void pritest(){
​
    }
​
public static void main(String[] args) {
     Demo1 demo1 = new Demo1();//There is no static, so create an object here
    System.out.println(demo1.pubname);
    System.out.println(demo1.proname);
    System.out.println(demo1.name);
    System.out.println(demo1.priname);  //Can be accessed in this class
​
 }
}
public class TestDemo1 extends Demo1{
    public static void main(String[] args) {
    Demo1 demo1 = new Demo1();
    System.out.println(demo1.pubname);
    //System.out.println(demo1.proname); Different packages, different classes of public permissions are still accessible
    //System.out.println(demo1.name);
​
    TestDemo1 testDemo1 = new TestDemo1();
    System.out.println(testDemo1.proname);//Protected members in the parent can be accessed in subclasses of different packages
  }
}

Access rights map:

Object Oriented Feature--Encapsulation

Hide some information of the class inside the class (implemented with access modifiers), do not allow direct access by external programs, prevent the attributes of the class from being modified and accessed arbitrarily by external code, and ensure the completeness of the data. Instead, use specific methods provided by the class to operate on and access hidden information for easy control.

  • Benefits of packaging

    • Hide the implementation details of the class so that the user only needs the effect and does not need to know the process.

    • Easy to add control statements.

    • It can only be accessed by prescribed methods.

    • It is easy to modify the implementation and improves the maintainability of the code without affecting external use.

  • Specific performance: use different access rights.

    public class Demo{ 
        private String name; 
        public String getName (){ 
        return name;
     } 
    public void setName(String name){
        this.name = name;
        }
     }
  • Case:

    public class Dog { 
       //Hide class properties
       private String name;
    public Dog() {
    ​
    }
    public Dog(String name) {
        if(name!=null){
            this.name = name;
        }
    }
      private void eat(){
    ​
       }
       //Provides specific methods for accessing hidden members
       public void setName(String name){//Method name lowercase
            if(name!=null){
                this.name = name;
            }
       }
    ​
       public String getName(){
            return this.name;
       }
    }
    ​
    public class TestDog {
         public static void main(String[] args) {
    ​
        Dog dog = new Dog("Prosperous Money");
            //dog.mame =';// Members of a direct access class cannot be accessed directly after being initialized with private s and are invoked by a constructor
        Dog dog1 = new Dog();
            dog1.setName("Little Black");
    ​
        System.out.println(dog1.getName());
        }
    }

For attributes, we do two things: save and fetch.

Get: return the property value, the return value type of the method is the same as the property type;

Set (storage): Receives the value you want to store in the parameter list, the solution (mode) when the type is the same as the attribute type.

Design Patterns: Solve a certain type of problem

Singleton mode: let a class create only one object in a program

public class WindowDemo {
//Receive the only object
 private static WindowDemo windowDemo = null;
​
/*
  Set the construction method to private permissions (privatization) and do not use it freely in other classes.
 */
private WindowDemo(){
​
}
​
//Provide methods to the outside world to get unique objects
public static  WindowDemo getWindow(){//This method must be static because private ly modified constructors cannot create objects outside
    //Controlling the number of generated objects
     if(windowDemo==null){
         windowDemo = new WindowDemo();
     }
     return    windowDemo;
  }
}
public class TestWindow {
public static void main(String[] args) {
​
     //new WindowDemo();
     //new WindowDemo();
​
   WindowDemo windowDemo1 =    WindowDemo.getWindow();
   WindowDemo windowDemo2 =  WindowDemo.getWindow();
​
    System.out.println(windowDemo1);
    System.out.println(windowDemo2);
  }
}

Posted by whitemoss on Sat, 04 Dec 2021 09:37:37 -0800