Java Basics - object oriented 1

4. Object oriented

  • Property + method becomes a class

Three main lines of Java object-oriented learning:
1.Java classes and class members: properties, methods, constructors; Code block, inner class
2. Three characteristics of object-oriented: encapsulation, inheritance, polymorphism, (abstraction)
3. Other keywords: this, super, static, final, abstract, interface, package, import

  • Object oriented programming idea?
    (class, object; three characteristics of object-oriented;...)
  • Talk about your understanding of classes and objects in object-oriented, and point out the relationship between them?

Class: it is the description of a class of things, abstract and conceptual content
Object: an entity that actually exists. new things exist in memory. An object is really created in memory and occupies a certain space in memory
Object: derived from class (new)

4.1. What is object-oriented

  • Object oriented programming (OOP), the core idea of Java

  • The essence of object - oriented programming is to organize code in the form of class and data in the form of object

  • Abstract extract similar

  • Three characteristics:

    • Package to package a thing, leaving an opening for taking it out
    • Inherited subclasses can inherit everything from the parent class, and multiple subclasses inherit the same thing
    • There are many forms of the same thing
  • From the perspective of epistemology, there are objects first and then classes. Objects are concrete things. Classes are abstract and abstract to objects

  • From the perspective of code operation, there are classes before objects. Classes are the template of objects

  • pass by value

 // pass by value
    public static void main(String[] args){
        int i = 1;
        System.out.println(i);
        Demo04.change(i);
        System.out.println(i);
        i = Demo04.change1(i);
         System.out.println(i);

    }
    // The return value is null
    public static void change(int a){
        a = 10;
    }
    // The return value cannot be empty
    public static int change1(int a){
        a = 10;
        return a;
    }
  • Reference passing
public class Demo05 {
    // A class can have multiple public class es, but it can have multiple classes
    // Reference passing: object, essence or value passing
    public static void main(String[] args) {
        // Person is a reference to an object in the heap
        Person person = new Person(); // Instantiate the Person object
        System.out.println(person.name); // null
//        Demo05.change(person);
        change(person); // The reference passes the address of the object
        System.out.println(person.name);// dijia
        // The memory address corresponding to the variable name is different
        // Value transfer. The value after transfer is changed without affecting the original variable
        // Therefore, only the variable in the method is pointed to the string, and the reference of the original variable of the main method is not changed
    }

    public static void change(Person person) {
        // Person is an object: it points to the class person
        // Or person = new person(); This is a specific person who can change attributes!
        person.name = "dijia";
    }
}

// Define a Person class with an attribute: name
class Person {
    String name;
}

4.2. Creating and initializing objects

  • Two elements of object orientation:
    • Class: the description of a class of things, which is an abstract and conceptual definition
    • Object: it is each individual of such things that actually exists, so it is also called instance
  • Creation of classes and objects

Embodiment of object-oriented thought I. creation and execution of classes and objects (implementation of object-oriented thought):
1. Create a class and design the members of the class
2. Create class objects
3. Call the structure of the object through "object. Attribute" or "object. Method()"
2, If you create multiple objects of a class, each object has a set of class properties independently (without static keyword)
This means that if we modify attribute a of one object, the value of another attribute a will not be affected. (static is a shareable attribute)

// Test class
public class PersonTest {
    // main method as program entry
    public static void main(String[] args) {
        // Object to create Person class = instantiation of class = instantiation of class
        Person p1 = new Person(); // Class is the type of object, object is the instance of class, and Person is the referenced variable type
        // The (function and behavior) structure of the calling object: properties and methods
        // Calling property: "object. Property;"
        p1.name = "tom";
        p1.isMale = true;
        System.out.println(p1.name);
        // Calling method: "object. Method ();"
        p1.eat();
        p1.sleep();
        p1.talk("Chinese");
        System.out.println("================");
        Person p2 = new Person();
        System.out.println(p2.name); // null
        System.out.println(p2.isMale); // false
        System.out.println("===================");
        //
        Person p3 = p1; // The address value of the p1 object is assigned to p3, resulting in p1 and p3 pointing to the same object entity in the heap space
        System.out.println(p3.name); // tom
        p3.age = 10;
        System.out.println(p1);
        System.out.println(p3);
        System.out.println(p1.age); // 10
    }
}
// Create class and design class members: including member methods and member variables
class Person{
    // Attribute = member, variable = domain, field
    String name;
    int age = 1;
    boolean isMale;

    // Design method: behavior
    public void eat(){
        System.out.println("People can eat");
    }
    public void sleep(){
        System.out.println("People can sleep");
    }
    public void talk(String language){
        System.out.println("People can talk and use:" + language);
    }
  • Memory resolution of object:
  • Stack features: first in and last out
    1.new Person(); First, an object is created, and the structure of new is in the heap, which means that an object entity is created in the heap space, and the object will have an address value called the first address value; A variable p1 is declared in the stack space. At this time, p1 is actually defined in the main method. The variables defined in the method are local variables. At this time, the data of the new structure is assigned to p1, which is actually assigned an address. After assigning the address value, p1 in the stack space points to the object entity created in the stack space. The class has declared three attributes during design, These attributes are different from local variables. The attributes exist in the heap space. In the created object, the default initialization value and previously assigned value will be given in the assignment process
    2. Find the structure of new through p1, call name, change null to Tom, and the assigned data of Tom is actually in the string constant pool in the method area
    3. Re create an object entity in the heap space. The entity has a first address value. Assign this address value to the variable p2 currently loaded in the stack space. The p2 object in the stack space can point to the object entity in the heap space. The object entity also independently generates a default initialization value and a previous value
    4. A p3 local variable is also declared in the main method (stack space). p3 takes the value assigned by p1. p1 stores the address value, so the address value passed to p3 is the same. The address value passed through p1 also points to the structure of p1 in heap space along the address. Therefore, p3 cannot be called a newly created object, but only a newly declared variable, At this point, p1 and p3 point to the same object entity in the heap space

4.3. Comparison between attributes and local variables

Use of properties in class
Attribute (member variable) vs local variable

  • 1. Similarities:
    • 1.1. Define variable format: data type variable name = variable value
    • 1.2. Declaration before use
    • 1.3. Each variable has its corresponding scope
  • 2. Differences:
    • 2.1. The positions declared in the class are different
      Attribute: directly defined in a pair {} of classes
      Local variable: declared in method, method parameter, code block, constructor parameter, variable inside constructor
    • 2.2. Different permissions modifiers
      Attribute: when declaring an attribute, you can specify its permission and use the permission modifier
      Common permission modifiers: private,public, default (equivalent to default),protected - > class encapsulation
      At present, when declaring properties, just use the default
      Local variable: permission modifiers cannot be used. It can be understood that its permission is replaced by the permission of the method
    • 2.3. Default initialization value:
      Attribute: the attribute of a class has a default initialization value according to its type
      Integer (byte,short,int,long): 0
      Float, double: 0.0
      Character type (char), 0 (or '\ u0000')
      Boolean: false
      Reference data type: (class (special String), array, interface): null
      Local variable: there is no initialization value, which means that the assignment must be displayed before calling the local variable
      In particular: the formal parameter can be assigned when called
    • 2.4. Where they are loaded in memory:
      (non static) attribute: loaded into heap space (static attributes are placed in the method area)
      Local variables: loading into stack space
public static void main(String[] args) {
        User u1 = new User();
        System.out.println(u1.name);
        System.out.println(u1.age);
        System.out.println(u1.isMale);
        u1.talk("chinese");
        u1.eat();
    }
}

class User{
    // Properties (member variables)
    String name; // private permissions are small, so you can't adjust this class if it's defined
    public int age; // public permissions are large, and those outside can be adjusted
    boolean isMale;

    public void talk(String language){ // language: formal parameter (local variable)
        System.out.println("We use" + language + "communication");
    }
    public void eat(){
        String food = "Flapjack"; // (declared) variables defined in a method are called local variables
        System.out.println("Northerners eat" + food);
    }

4.4. Null pointer exception

About garbage collector: GC
In the Java language, garbage collector mainly aims at heap memory
When a Java object has no reference to the object,
GC will consider releasing and recycling the garbage data

  • The precondition for null pointer exception is?
    • Null pointer exceptions will occur when a null reference accesses data related to an instance (object, such as id)
/*
    Null pointer exception
 */
public class NullPointerTest {
    public static void main(String[] args) {
        // Create customer object
        Customer1 c1 = new Customer1();
        // Access this customer object
        System.out.println(c1.id);
        // Reassign id
        c1.id = 242;
        System.out.println(c1.id);
        c1 = null;
        // Null pointerexception null pointer exception
        // The compiler has no problem, because the compiler only checks the syntax. The compiler finds that c is a Customer type,
        // The Customer type consists of an ID attribute, so you can call c.id. the syntax is too high,
        // However, the existence of the object is required during operation, but if the object is lost, only exceptions can occur
        System.out.println(c1.id);
    }
}
// Customer class
class Customer1{
    // Customer id attribute
    int id; //  The instance variable in the member variable should be created first, and then accessed by "reference"
}

4.5. Object array

public class StudentTest1 {
    public static void main(String[] args) {
        // Declare an array of objects of custom class Student type
        Student1[] stus = new Student1[20]; // Similar to String[] arr = new String [];
        for (int i = 0;i < stus.length;i++){
            // Assign values to array elements
            stus[i] = new Student1();
            // Assign a value to the property of the Student object
            stus[i].number = (i + 1);
            // Grade: [1,6]
            // Random number a~b formula: int value = (int)(Math.random() * (b - a + 1) - a)
            stus[i].state = (int)(Math.random() * (6 - 1 + 1) + 1);
            // Score: [0 ~ 100]
            stus[i].score = (int)(Math.random() * (100 - 0 + 1));
        }
        // To call other methods in the main method, create an object of the current class in the public class of the main method,
        StudentTest1 test = new StudentTest1();
        // Traverse student array
        test.print(stus);
        /*for (int i = 0;i < stus.length;i++){
            // stus[i].info();
            System.out.println(stus[i].info2());
        }*/

        System.out.println("======================");
        // Print the student information of the third grade (state value is 3)
        test.searchState(stus,3);
        /*for (int i = 0;i < stus.length;i++){
            if (stus[i].state == 3){
                stus[i].info();
            }
        }*/
        System.out.println("========================");
        // Use bubble sort to sort by student grade and traverse all student information
       /* for (int i = 0;i < stus.length - 1;i++){
            for (int j = 0;j < stus.length - 1 - i;j++){
                if (stus[j].score > stus[j+1].score){
                    // Here we want to exchange the objects of array elements! It means exchanging the whole person
                    // If only the results are exchanged, the student number and grade are not changed, which is equivalent to "cheating"
                    Student1 temp = stus[j];
                    stus[j] = stus[j+1];
                    stus[j+1] = temp;
                }
            }
        }*/
        /*for (int i = 0;i < stus.length;i++){
            System.out.println("Student number: "+ stus[i].number +" grade: "+ stus[i].state +" score: "+ stus[i].score);
        }*/
    }
    // Operation of traversing Student1 [] type array

    /**
     * @Description Operation of traversing Student1 [] type array
     * @author tiga
     * @date time
     * @param stus
     */
    public void print(Student1[] stus){ // Pass in formal parameter of Student1 [] type array
        for (int i = 0;i < stus.length;i++){
            stus[i].info();
        }
    }
    // Find student information of a grade
    /**
     *
     * @Description Find the Student information of the specified grade in the Student type array
     * @author tiga
     * @date time
     * @param stus Array to find
     * @param state Grade to find
     */
    public void searchState(Student1[] stus,int state){ // Pass in the array to find and the grade to find as formal parameters
        for (int i = 0;i < stus.length;i++){
            if (stus[i].state == state){
                System.out.println(stus[i].info2());
            }
        }
    }
    // Bubble sort student scores and traverse student information
    public void sort(Student[] stus){
        for (int i = 0;i < stus.length - 1;i++){
            for (int j = 0;j < stus.length - 1 - i;j++){
                if (stus[j].score > stus[j+1].score){
                    Student temp = stus[j];
                    stus[j] = stus[j+1];
                    stus[j+1] = temp;
                }
            }
        }
    }
}

class Student1{
    int number; // Student number
    int state; // grade
    int score; // achievement

    public void info(){
        System.out.println("Student number:" + number + "grade:" + state + "achievement:" + score);
    }
    public String info2(){
        return "Student number:" + number + "grade:" + state + "achievement:" + score;
    }
}
  • Memory parsing of object array

Reference type variables can only store null or object address values (including variable types)

4.6. Anonymous objects

1, Understand "everything is an object"
1. In the category of Java language, functions and structures are encapsulated into classes, and specific function structures are called through class instantiation
Scanner,String
Files: File
Network resource: URL
2. When it comes to the interaction between the Java language and the front-end HTML and the back-end database, the front and back-end structures are embodied as classes and objects at the Java level
2, Description of memory parsing:
1. Variables of reference type can only store two types of values: null or address value (including variable type)
3, Use of anonymous objects
1. Understanding: the created object is not explicitly assigned to a variable name, that is, it is an anonymous object
2. Feature: anonymous objects can only be called once
3. Use: anonymous objects can be put into methods and called multiple times

  • Simple memory analysis

In the calling method, the object of new Phone class will also have an address value in the space generated in the heap. When calling, the new object is actually assigned to the method in the definition class as a formal parameter, and the formal parameter is a local variable, and the variable will be stored in the stack, which is equivalent to assigning the address value of the object of new Phone class to the formal parameter. As long as it is assigned to the variable, the object can be more Once used, so that the formal parameter points to the new object in the heap, and other methods can be called through the address of the new object. At this time, the same anonymous object is called, which is equivalent to assigning the anonymous object to the famous object (formal parameter)

public class InstanceTest {
    public static void main(String[] args) {
        Phone p = new Phone(); // p is the variable name of the Phone object
//        p = null;
        System.out.println(p);
        p.sentEmail();
        p.playGame();
        // Anonymous object
        // Both call different objects
        new Phone().sentEmail();
        new Phone().playGame();
        new Phone().price = 2000;
        new Phone().showPrice(); // 0.0
        System.out.println("======================");
        // Use of anonymous objects
        PhoneMall mall = new PhoneMall();
        mall.show(new Phone()); // Theoretically anonymous
        ShowAddress add = new ShowAddress();
        add.printAdd(new PhoneMall());
    }
}
class ShowAddress{
    public void printAdd(PhoneMall phone){
        System.out.println(phone);
    }
}
class PhoneMall{
    public void show(Phone phone){ // In fact, the formal parameter is the name of the anonymous function
        phone.sentEmail();
        phone.playGame();
    }
}
class Phone{
    double price; // Price
    public void showPrice(){
        System.out.println("What is the price of mobile phone:" + price);
    }
    public void sentEmail(){
        System.out.println("Send mail");
    }
    public void playGame(){
        System.out.println("play a game");
    }
}
  • Understand the assignment of variables
  • When a local variable of basic data type is defined in the method, its variable is stored in the stack. The number assigned to the variable is what the variable is stored in the stack memory. The assignment transfer between variables is also the transfer number
int m = 10;
int n = m; // n == 10
  • When a local variable of reference type is defined in the method, its variable is also stored in the stack, but the address value of the value assigned by the variable. Therefore, when assigning and passing between variables of the same type, the address is passed, not the number
  • Value Passing Mechanism: for basic data types

1, Method: Value Passing
1. Formal parameter: parameter in parentheses declared during method definition
2. Argument: the data actually passed to the formal parameter during method call can be either a specific number or a variable
2, Value Passing Mechanism: if the parameter is a basic data type, the real stored data value of the parameter is assigned to the formal parameter

  • Memory analysis

1. Reasons why m and n are not replaced: in the stack, first come in from the main method, and m and n defined in the main method are assigned 10 and 20 respectively;
2. When the swap method is called by the object v, V will not write in. When the swap method is called, the above parameters m and N represent the value of data, and are assigned to the formal parameters m and n (newly defined) of the following swap method. These two formal parameters are also provided in the stack. The formal parameters m and N are assigned by the actual parameters, also 10 and 20. At this time, m and N are in the swap method;
3. Then v call the swap method to enter the method execution. As soon as you enter the method, you declare a new variable temp. Temp takes the value assigned by the formal parameter m, then gives the value of the formal parameter n to m, and then gives temp to N. the most effective implementation effect of the swap method is to exchange M and N in the swap method. If it is output in the method, m and N will be exchanged, but if it is not output in the method, the swap method will be destroyed after execution (out of the stack) After destruction, it is output under the main method. The output values of M and N are the values assigned by the main method, because after the swap method is out of the stack, the output values of M and N are the values of M and n variables defined in main, and the variables defined in main are valid in the whole brace area of main. Therefore, the output in main is still the value defined in main, so the two numbers are not replaced with. Array elements The same is true for the value exchange of prime

public static void main(String[] args) {
        int m = 10;
        int n = 20;
        System.out.println(m + "," + n);
        ValueTransferTest1 test = new ValueTransferTest1();
        test.swap(m,n); // Argument
        /*int temp = m;
        m = n;
        n = temp;*/
        System.out.println(m + "," + n); // 10, 20
    }
    public void swap(int m,int n){ // The formal parameter passed in by the new variable argument
        int temp = m;
        m = n;
        n = temp;
        // System.out.println(m + "," + n);
    }

  • Value Passing Mechanism: for reference data types
    A static method calls a non static method by first creating a new object
    Static method call static method direct call
    Non static method call non static method direct call

  • Memory analysis

1. Enter the main method, create a new data variable in the stack and an object in the heap space. The object will have an address value, and assign the address value to the data variable in the stack space. Through the address value, the data variable in the stack space points to the object entity in the heap space
2. Next, the Data (object) variable calls the variables m and N defined in the Data class. At first, the initial values of M and N are 0. The values of M and N are changed through the object call attribute. At this time, the output is 10 and 20
3. Then, the new object calls the swap method and passes in the reference type data as the formal parameter. The passed in reference type data is the above argument, so the formal parameter is the reference type, and the address value is stored. Loading the formal parameter in the stack is equivalent to copying the address value of data in the main method. After the formal parameter has the address value, it points to the same object entity in the heap space
4. Enter the swap method body, call the value of m through the data (formal parameter) variable, and assign it to a local variable temp declared inside the swap method. Temp is also loaded in the stack. The value of n of data is assigned to m of data, and the value of temp is assigned to n of data. So far, the execution of the method is completed. After that, the temp and data variables defined by the swap method are out of the stack, and the pointer to the formal parameter data is gone, but the objects in the heap are still there, There is also the point of the argument data, so that it can be judged that the objects in the heap are not garbage and cannot be recycled
5. Return to the main method, and then execute the output data.m and data.n. these two data variables are the actual parameters data, and the values of M and n are exchanged

  • Exercise: parameter passing for methods

4.7. Object oriented feature 1: encapsulation and hiding

Object oriented feature 1: encapsulation and hiding
1, Introduction of problems:
After we create a class object, we can assign the attribute of the object by means of "object. Attribute". Here, the assignment operation should be restricted to the data type and storage range of the attribute
In addition, there are no other constraints, but in practical problems, we often need to add additional restrictions and price adjustment to attribute assignment. This special condition cannot be reflected in attribute declaration. We can only add restrictions through methods (such as setLegs())
At the same time, we need to prevent users from using the "object. Attribute" method to assign values to attributes, so we need to declare the attributes private
– > at this time, the encapsulation is reflected for attributes
2, One embodiment of encapsulation (not equivalent to encapsulation):
Privatize the property xxx of the class, and provide a public method to get (getXxx) and set (setXxx) the value of this property
Expansion: embodiment of encapsulation: 1. Above 2. Private method without external exposure 3. Singleton mode: privatize the constructor
3, The embodiment of encapsulation requires permission modifiers
1. Four kinds of permissions specified by Java (from small to large): private, default, protected and public
2.4 kinds of permissions can be used to modify classes and the internal structure of classes: attributes, methods, constructors, internal classes, (code blocks do not work)
3. Specifically, the permissions in 4 can be used to modify the internal structure of a class: attributes, methods, constructors, and internal classes
If you modify a class, you can only use: default, public, not private
Summary encapsulation: Java provides four permission modifiers to modify the class and the internal structure of the class, reflecting the visibility of the class and the internal structure of the class when called
Embodiment 1: privatize the attribute xxx of the class, and provide a public method to obtain (getXxx) and set (setXxx) the value of this attribute
Embodiment 2: private method without external exposure
Embodiment 3: Singleton mode (the constructor is privatized. The constructor cannot be adjusted outside. Only one object is created inside, and everyone uses only one object)
Embodiment 4: if you do not want the class to be called outside the package, you can set the class as the default

public class AnimalTest {
    public static void main(String[] args) {
        Animal a = new Animal();
        a.name = "chinese rhubarb";
        // a.age = 1; //  After the property is privatized, it cannot be called directly. It should be called through the public method
        // a.legs = 4; //  The field Animal.legs is not visible
        a.show(); // The property value displayed in the show method is the property value of the person who calls the show method
        a.setLegs(-6);
        // a.legs = -4; // The field Animal.legs is not visible
        a.show();
    }
}
class Animal{
    String name;
    private int age;
    // private benefits: setLegs provides a method to assign values to legs and add judgment conditions. It can also disable direct attribute calls
    // At this point, the encapsulation of the legs attribute can be achieved, which is equivalent to that this attribute is not exposed
    private int legs; // The number of legs is limited to private rights first, visible, but cannot be called outside the class
    public void setLegs (int l){
        if (l >= 0 && l % 2 == 0){
            legs = l;
        }else{
            legs = 0;
            // Another way of writing is to throw an exception (I haven't talked about it yet)
        }
    }
    public int getLges(){
        return legs;
    }
    public void eat(){
        System.out.println("Animal feeding");
    }
    public void show (){
        System.out.println("name = " + name + ",age = " + age + ",legs = " + legs);
    }
    // Provides get and set methods for the attribute age
    public int getAge(){
        return age;
    }
    public void setAge(int a){
        age = a;
    }
}
  • Exercise: basic use of encapsulation
public class PersonTest {
    public static void main(String[] args) {
        Person p1 = new Person();
        // p1.age = 1; //  After the age is privatized, it cannot be called directly, and the compilation fails
        p1.setAge(12);
        System.out.println("Age is:" + p1.getAge());
    }
}
public class Person {
    private int age;
    public void setAge(int a){
        if (a < 0 || a > 130){
            // throw new RuntimeException("illegal incoming data")// [[throw exception
            System.out.println("Illegal incoming data");
            return; // End method
        }
        age = a;
    }
    public int getAge(){
        return age;
    }
    // Never write the setting and obtaining methods together! These writing methods are meaningless
    /*public int doAge(int a){
        age = a;
        return a;
    }*/
}

4.8. Class member 3: constructor (or constructor)

  • The third structure of a class is the use of constructors (or constructors (c + +) or construction methods, but different from methods, constructors)
    construction constructor: constructor
  • 1, Function of constructor:
    1. Create object
    2. Initialize the properties of the object
  • 2, Description:
    1. If there is no explicit definition of class constructor, the default parameterless constructor is provided by default
    2. Define the format of constructor (different from method): permission modifier class name (formal parameter list) {}
    3. Multiple constructors are defined in a class to form overloads with each other
    4. Once we explicitly define the class constructor, the system will no longer provide the default non (empty) parameter constructor (for example, the state poverty subsidy can be used)
    5. There will be at least one constructor in a class. (equivalent to giving us the ability to create objects. Only with a constructor can we create objects) (it may be default or written by ourselves)
public class PersonTest {
    public static void main(String[] args) {
        // Create object of class (use of constructor): new + constructor (constructor and class have the same name)
        Person p = new Person(); // I defined an explicit constructor myself
        p.eat();
        Person p1 = new Person("tom");
        System.out.println(p1.name);
    }
}

class Person{
    int age;
    String name;
    // constructor 
    public Person(){
        // It can be used to initialize this class. When instantiating this class, you need to pass values instead of calling methods
        // The code in the constructor is executed when the new object is created
        System.out.println("Person().....");
    }
    // Overload of constructor
    public Person(String n){ // The function of formal parameters is to initialize the current properties of the created object
        name = n; // name: attribute of the object currently being created
    }
    public Person(String n, int a){
        name = n;
        age = a;
    }
    public void eat(){
        System.out.println("People eat");
    }
    public void study(){
        System.out.println("People sleep");
    }
}
  • Exercise: basic use of constructors

1. Create a program and define two classes: Person and PersonTest. The definitions are as follows:
Use setAge() to set the legal age of the heat (0 ~ 130), and use getAge() to return the age of the person
2.1. Add a constructor to the previously defined Person class, and use the constructor to set the initial value of age attribute of everyone to 18
2.2. Modify the class and constructor in the above question and add the name attribute to initialize the age attribute value and name attribute value of the object every time the Person object is created
3. If at least one constructor is provided in the class but no null parameter constructor is provided, it is illegal to construct an object without providing parameters. That is, an error will be reported when creating an object without formal parameters

/*
 * Instantiate the object b of the Person class in the Person test class
 * Call setAge() and getAge() methods to experience the encapsulation of Java
 */
public class PersonTest {
    public static void main(String[] args) {
        Person p1 = new Person();
        // p1.age = 1; //  After the age is privatized, it cannot be called directly, and the compilation fails
         p1.setAge(12);
        // p1.getAge(); // age == 18
        System.out.println("Age is:" + p1.getAge());
        Person p2 = new Person("tom", 21);
        // After the property is privatized, it can only be called through methods
        System.out.println("name: " + p2.getName() + ", age: " + p2.getAge());
    }
}
public class Person {
    // Code order: attribute -- > constructor -- > method
    private int age;
    private String name;
    public Person(){
        age = 18;
    }
    // It embodies the parametric constructor
    public Person(String n, int a){
        name = n;
        age = a;
    }
    public void setAge(int a){
        if (a < 0 || a > 130){
            // throw new RuntimeException("illegal incoming data")// Throwing anomaly
            System.out.println("Illegal incoming data");
            return; // End method
        }
        age = a;
    }
    public int getAge(){
        return age;
    }
    // It reflects the encapsulation
    public void setName(String n){
        name = n;
    }
    public String getName(){
        return name;
    }
    // (wrong writing) never write the methods of setting and obtaining together! These writing methods are meaningless
    /*public int doAge(int a){
        age = a;
        return a;
    }*/
}
  • Constructor exercise: triangles
/*
 * Write two classes, TriAngle and TriAngleTest, in which TriAngle class declares private bottom long base and high H eight, and declares public methods to access private variables
 * Here, the necessary constructors for class are provided. These common methods are used in another class to calculate the area of a triangle
 */
public class TriAngleTest {
    public static void main(String[] args) {
        TriAngle t1 = new TriAngle();
        t1.setBase(3.2); // Equivalent to passing in arguments
        t1.setHeight(4.66);
        System.out.println("base: " + t1.getBase() + ", height: " + t1.getHeight());
        // On the one hand, the constructor can create objects and assign values to the properties of the corresponding objects
        TriAngle t2 = new TriAngle(5.1, 4.6);
        System.out.println("base: " + t2.getBase() + ", height: " + t2.getHeight());
    }
}
public class TriAngle {

    private double base;
    private double height;

    public TriAngle(){

    }
    public TriAngle(double b,double h){
        base = b;
        height = h;
    }
    public void setBase(double b){
        base = b;
    }
    public double getBase(){
        return base;
    }
    public void setHeight(double h){
        height = h;
    }
    public double getHeight(){
        return height;
    }
}
  • Summary: sequence of attribute assignment

1. Default initialization (default value of class attribute)
2. Explicit initialization (assigning values to attributes in the class)
3. Initialization (assignment) in constructor
=The above three operations can only be performed once, and the following operations can be performed repeatedly===
4. Assign values through "object. Attribute" without encapsulation or through "object. Method name ()" after encapsulation
The sequence of the above operations: 1 - 2 - 3 - 4, covering from the back to the front, and the front appears as a process

public class UserTest {
    public static void main(String[] args) {
        User u = new User();
        System.out.println(u.age);
        User u1 = new User(2);
        u1.setAge(3);
        System.out.println(u1.age);
    }
}
class User{
    String name;
    int age = 1;
    public User(){

    }
    public User(int a){
        age = a;
    }
    public void setAge(int a){
        age = a;
    }
}

4.9. Keyword: use of this - this calls properties and methods

Use of this keyword:

  • 1.this can be used to modify: properties, methods, constructors
  • 2.this modification attribute and method:
    this is understood as: the current object or the object currently being created
    • 2.1. In the method of class, we will use "this. Attribute" or "this. Method" to call the current object attribute or method
      However, usually, we choose to omit "this." in special cases, if the formal parameter of the method has the same name as the attribute of the class, we must explicitly use "this. Variable" to indicate that the variable is an attribute rather than a formal parameter
    • 2.2. In the constructor of a class, we can use "this. Attribute" or "this. Method" to call the object attribute or method currently being created. However, in general, we choose to omit "this." in special cases, if the formal parameter of the constructor has the same name as the attribute of the class, we must explicitly use "this. Variable" to indicate that this variable is an attribute rather than a formal parameter
public class PersonTest {
    public static void main(String[] args){
        Person p1 = new Person(); // Use the default null argument constructor
        p1.setAge(1);
        System.out.println(p1.getAge());
        p1.eat();
    }
}

class Person{
    private String name; // Member variable (property) of class
    private int age;
    public Person(){
        this.eat(); // Call the eat method of the object currently being created
    }
    // this in constructor: the object currently being created
    public Person(String name){
        this.name = name; // Properties of the object currently being created
    }
    public Person(int age){
        this.age = age;
    }
    public Person(String name, int age){
        this.name = name;
        this.age = age;
    }
    public void setName(String name){ // There is no error when an attribute and a formal parameter (local variable) have the same name. Because their positions are different, one is in the class and the other is in the method
        this.name = name; // The principle of proximity gives priority to the variable name of proximity
    }
    public String getName(){
        return this.name;
    }
    public void setAge(int age){ // age = 1
        // age = age; // 1 = 1, which has nothing to do with the attribute age
        // this: can be understood as the current object, equivalent to p1
        this.age = age; // The property / method of the current object is called by the object, and both methods or properties are used by points
    }
    public int getAge(){
        return this.age;
    }
    public void eat(){
        System.out.println("People eat");
        this.study();
    }
    public void study(){
        System.out.println("Human learning");
    }
}
  • this call constructor

Use of this keyword:
1.this can be used to modify: properties, methods, constructors
2.this modification attribute and method:
this is understood as: the current object or the object currently being created
2.1. In the method of class, we will use "this. Attribute" or "this. Method" to call the current object attribute or method
However, usually, we choose to omit "this.". In special cases, if the formal parameter of the method has the same name as the attribute of the class,
You must explicitly use "this. Variable" to indicate that this variable is an attribute, not a formal parameter
2.2. In the class constructor, we can call the object property or method currently being created by using "this. Property" or "this. Method",
However, in general, you choose to omit "this." in special cases, if the formal parameter of the constructor has the same name as the attribute of the class, you must explicitly
Using "this. Variable" means that this variable is an attribute, not a formal parameter
3.this call constructor
(1) In the constructor of this class, you can explicitly use the "this (formal parameter list)" method to call other constructors specified in this class
(2) Constructor cannot call itself by "this (formal parameter list)"
(3) If there are n constructors in a class, "this (formal parameter list)" is used in up to n-1 constructors
(4) Specifies that "this (formal parameter list)" must declare the first line of the current constructor
(5) Inside the constructor, at most one "this (formal parameter list)" can be declared to call other constructors

public class PersonTest {
    public static void main(String[] args){
        Person p1 = new Person(); // Use the default null argument constructor
        p1.setAge(1);
        System.out.println(p1.getAge());
        p1.eat();
        System.out.println();
        // Constructor multiple calls only create an object, but when calling other constructors, the logic borrows the logic of other constructors
        // No matter how you call the constructor, you end up creating an object
        Person p2 = new Person("Harry", 20);
        System.out.println(p2.getAge());
        System.out.println(p2.getName());
    }
}

class Person{
    private String name; // Member variable (property) of class
    private int age;
    public Person(){
        // this.eat(); //  Call the eat method of the object currently being created
        // this(); //  Empty parameter constructors can't adjust themselves, they will loop, and the two constructors can't callback
        String info = "Person During initialization,Consider the following 1,2,3,4...(40 lines of code)";
        System.out.println(info);
    }
    // this in constructor: the object currently being created
    public Person(String name){
        this(); // Call the constructor's method. The parameters are the constructor
        this.name = name; // Properties of the object currently being created
    }
    public Person(int age){
        this();
        this.age = age;
    }
    public Person(String name, int age){
        this(age);
        this.name = name; // Reinitialize the independent name
        // this.age = age;  It can be omitted after calling the above constructor
    }
    public void setName(String name){ // There is no error when an attribute and a formal parameter (local variable) have the same name. Because their positions are different, one is in the class and the other is in the method
        this.name = name; // The principle of proximity gives priority to the variable name of proximity
    }
    public String getName(){
        return this.name;
    }
    public void setAge(int age){ // age = 1
        // age = age; // 1 = 1, which has nothing to do with the attribute age
        // this: can be understood as the current object, equivalent to p1
        this.age = age; // The property / method of the current object is called by the object, and both methods or properties are used by points
    }
    public int getAge(){
        return this.age;
    }
    public void eat(){
        System.out.println("People eat");
        this.study();
    }
    public void study(){
        System.out.println("Human learning");
    }
}
  • Comprehensive exercise

public class CustomerTest {
    public static void main(String[] args) {
        Customer cust = new Customer("Jane", "Smith");
        Account acct = new Account(1000, 2000, 0.0123); // Declaration constructor
        cust.setAccount(acct); // The bank got the card number after handling the card
        cust.getAccount().deposit(100); // Application of class variables
        cust.getAccount().withdraw(960);
        cust.getAccount().withdraw(2000);
        System.out.println("Customer [" + cust.getLastName() + ","
                + cust.getFirstName() + "] has a account: id is "
                + cust.getAccount().getId() + ", annualInterrestRate is"
                + cust.getAccount().getAnnualInterestRate() * 100
                + "%, balance is " + cust.getAccount().getBalance());
    }
}
public class Account {
    private int id; // account number
    private double balance; // balance
    private double annualInterestRate; // Annual interest rate

    // constructor 
    public Account(int id,double balance,double annualInterestRate){
        this.id = id;
        this.balance = balance;
        this.annualInterestRate = annualInterestRate;
    }
    public void setId(int id){
        this.id = id;
    }
    public int getId(){
        return this.id;
    }
    public void setBalance(double balance){
        this.balance = balance;
    }
    public double getBalance(){
        return this.balance;
    }
    public void setAnnualInterestRate(double annualInterestRate){
        this.annualInterestRate = annualInterestRate;
    }
    public double getAnnualInterestRate(){
        return this.annualInterestRate;
    }
    public void withdraw(double amount){ // Withdraw money
        if (balance < amount){
            System.out.println("Sorry, your credit is running low,Withdrawal failed");
            return; // It has the same effect as else
        }
        balance -= amount;
        System.out.println("Successfully removed" + amount);
    }
    public void deposit(double amount){ // save money
        if (amount > 0){
            balance += amount;
            System.out.println("Successfully deposited" + amount);
        }
    }
}
public class Customer {
    private String firstName;
    private String lastName;
    private Account account;

    // constructor 
    public Customer(String f,String l){
        this.firstName = f;
        this.lastName = l;
    }
    public String getFirstName(){
        return this.firstName;
    }
    public String getLastName(){
        return this.lastName;
    }
    public void setAccount(Account account){
        this.account = account;
    }
    public Account getAccount(){
        return this.account;
    }
}
  • Comprehensive exercise 2: object array
public class BankTest {
    public static void main(String[] args) {
        Bank bank = new Bank();
        bank.addCustomer("Jane","Smith");
        // Continuous operations may have null pointers, and methods can operate continuously only if they have a return value
        bank.getCustomer(0).setAccount(new Account(2000));
        bank.getCustomer(0).getAccount().withdraw(500);
        double balance = bank.getCustomer(0).getAccount().getBalance();
        System.out.println("customer:" + bank.getCustomer(0).getLastName() + "Your account balance is: " + balance);
        bank.addCustomer("a great distance","Yang");
        System.out.println("Number of bank customers: " + bank.getNumberOfCustomers());
    }
}
public class Customer {
    private String firstName;
    private String lastName;
    private Account account;

    // constructor 
    public Customer(String f,String l){
        this.firstName = f;
        this.lastName = l;
    }

    // get,set method
    public String getFirstName(){
        return this.firstName;
    }
    public String getLastName(){
        return this.lastName;
    }
    public void setAccount(Account acct){
        this.account = acct;
    }
    public Account getAccount(){
        return this.account;
    }
}
public class Account {
    private double balance;

    public Account(double init_balance){
        this.balance = init_balance;
    }

    // Balance query
    public double getBalance(){
        return this.balance;
    }
    // Saving operation
    public void deposit(double amt){
        if (amt > 0){
            balance = balance + amt;
            System.out.println("Deposit successful");
        }
    }
    // Withdrawal operation
    public void withdraw(double amt){
        if (balance > amt){
            balance = balance - amt;
            System.out.println("Successful withdrawal");
        }else{
            System.out.println("Sorry, your credit is running low");
        }
    }
}
public class Bank {
    // The variable is defined and not initialized, but the property has been initialized by default. At this time, the default value is null
    private Customer[] customers; // An array that holds multiple users
    private int numberOfCustomers; // Record the number of customers
    // constructor 
    public Bank(){
        customers = new Customer[10]; // First, give the array initialization space. Because the permission is private, you can't initialize in the test class main
    }
    // Add customer method
    public void addCustomer(String f,String l){
        // cust is a customer type variable, and the array defined above is also of customer type, so it can be assigned
        Customer cust = new Customer(f, l);
        // customers[numberOfCustomers] = cust; //  customers[numberOfCustomers] = new Customer(f,l); Array elements are statically assigned in the constructor
        // numberOfCustomers++;
        // customers = new Customer[10]; //  Array space initialization cannot be written here, because it was originally written in the constructor to create an array, then drop a method to save one person, and then adjust the method to save another person. Writing in the method becomes, first adjust the method to create an array, then save one person, and then adjust the method again to create an array and then save another person
        customers[numberOfCustomers++] = cust;
    }
    // Method for obtaining the number of customers
    public int getNumberOfCustomers(){
        return numberOfCustomers;
    }
    // Method to get the customer at the specified location
    public Customer getCustomer(int index){
        // return customers[index]; //  It cannot be written like this, and an exception may be reported. 1. When the array is not initialized, it may have a null pointer. 2. After the array is initialized, the array subscript may be out of bounds. 3. The index may not exceed the length of the array, but it may not be greater than the number of actually stored array elements
        if (index >= 0 && index < numberOfCustomers){ // The index value is less than the number of customers because the first customer is placed in position 0
            return customers[index];
        }
        return null;
    }
}

4.10.1. Use of package keyword

  • 1. In order to better realize the management of classes in the project, the concept of package is provided
  • 2. Use package to declare the package to which the class or interface belongs, which is declared in the first line of the source file
  • 3. The package is an identifier, which follows the naming rules of the identifier, specification (xxx.yyy.zzz), "see the meaning of the name"
  • 4. Every "." represents a layer of file directory
    Supplement: interfaces and classes with the same name cannot be named under the same package
    Under different packages, you can name interfaces and classes with the same name

4.10.2. Use of import keyword

5.1. Object oriented feature 2: understanding of inheritance

1. Why should there be class inheritance? (inherited benefits)

1. Reduce code redundancy and improve code reusability
2. Facilitate function expansion: directly declare the functions that all subclasses want to expand in the parent class, and the subclasses can get them directly because they inherit
3. It provides a premise for the use of polymorphism

2. Format of inheritance:

class A extends B{}
A: Subclass, derived class, subclass
B: Parent class, superclass, base class, superclass

3. What are the differences after a child class inherits the parent class?

2.1. Embodiment: once subclass A inherits parent class B, subclass A obtains all the attributes and methods declared in parent class B (used to call)
In particular, for the property or method declared private in the parent class, after the child class inherits the parent class, it is still considered to have obtained the private structure in the parent class
Only because of the influence of encapsulation, the subclass cannot directly call the structure of the parent class
2.2. After inheriting the parent class, a subclass can also declare its own unique attributes or methods to expand its own unique functions
The relationship between a subclass and a parent class is different from that between a subset and a set (some subclasses of a parent class must have, while some subclasses of a child class do not necessarily have)

4. Description of inheritance in Java

1. A parent class can be inherited by multiple subclasses
2. Single inheritance of * * class in Java: * * a class can only have one parent class; (multiple interfaces can be inherited)
3. Child parent class is a relative concept
4. The parent class directly inherited by the child class is called: direct parent class; The parent class of indirect inheritance is called indirect parent class
5. After the subclass inherits the parent class, it obtains the properties and methods declared in the direct parent class and all indirect parent classes

public class ExtendsTest {
    public static void main(String[] args) {
        Person p1 = new Person();
        // p1.age = 1;
        p1.eat();
        Student s1 = new Student();
        // s1.age = 1;
        s1.eat(); // The method of privatization was also inherited,
        // s1.sleep();
        s1.setAge(10);
        System.out.println(s1.getAge());
        s1.breath();
        Creature c = new Creature();
        System.out.println(c.toString());
    }
}
public class Creature {
    public void breath(){
        System.out.println("breathing");
    }
}
public class Person extends Creature {
    private int age;
    String name;
    // Define constructor
    public Person(){

    }
    public Person(String name, int age){
        this.name = name;
        this.age = age;
    }
    // Definition method
    public void eat(){
        System.out.println("having dinner");
        sleep();
    }
    private void sleep(){
        System.out.println("sleep");
    }
    public void setAge(int age){
        this.age = age;
    }
    public int getAge(){
        return this.age;
    }
}
// Student inherits the properties and functions of the Person class
public class Student extends Person{
    // The defined in Person can be omitted
    /*String name;
    int age;*/
    String major; // Professionals who are not satisfied with inheritance can create new ones themselves
    // Duplicate names of constructor and class definitions cannot be deleted
    public Student(){

    }
    public Student(String name,int age, String major){
        this.name = name;
        setAge(age);
        this.major = major;
    }
    // Definition method
    /*public void eat(){
        System.out.println("");
    }
    public void sleep(){
        System.out.println("Sleep ");
    }*/
    // The unique method cannot be deleted
    public void study(){
        System.out.println("study");
    }
    public void show(){
        System.out.println("name: " + name + ", age = " + getAge());
    }
}
  • Inherited exercises:
public class CylinderTest {
    public static void main(String[] args) {
        Cylinder cy = new Cylinder();
        cy.setRadius(1.2);
        cy.setLength(3.4);
        double volume = cy.findVolume();
        System.out.println("The volume of the cylinder is: " + volume);
        // When the findArea method is not overridden
        /*double area = cy.findArea();
        System.out.println("Area of bottom circle: "+ area";*/
        // After overriding the findArea method
        double area = cy.findArea();
        System.out.println("Surface area of cylinder: " + area);
        System.out.println("========================");
        // The null parameter constructor of the parent class is called by default to reflect the subclass: super()
        Cylinder cy1 = new Cylinder(); // Output: 3.1415926
        double volume1 = cy1.findVolume();
        System.out.println("The volume of the cylinder is: " + volume1);
    }
}
public class Circle {
    private double radius; // radius
    public Circle(){
        radius = 1.0;
    }
    public Circle(double radius){
        this.radius = radius;
    }
    public void setRadius(double radius){
        this.radius = radius;
    }
    public double getRadius(){
        return this.radius;
    }
    // Calculated area
    public double findArea(){
        return Math.PI * radius * radius;
    }
}
/*
 * If the parent empty parameter constructor is commented out, the child empty parameter constructor reports an error because the child constructor first executes the parent empty parameter constructor super(); while the parent class does not have an empty parameter constructor
 * If the null parameter constructor of the subclass is commented out again, the subclass class name will report an error, because the subclass has the null parameter constructor provided by the system by default, and the constructor still calls the null parameter constructor super() of the parent class, while the parent class has no null parameter constructor
 */
public class Cylinder extends Circle{
    private double length;
    public Cylinder(){
        // In fact, there is a super(); / / the object is created through the subclass constructor. As soon as he comes up, he runs to the initialization radius of the parent class empty parameter constructor
        length = 1.0;
    }
    public void setLength(double length){
        this.length = length;
    }
    public double getLength(){
        return this.length;
    }
    // Returns the cylinder volume
    public double findVolume(){
         // return Math.PI * getRadius() * getRadius() * length;
        // return findArea() * getLength(); / / the subclass overwrites the parent method. Now it calls the findArea method of the subclass, so this method cannot be used to calculate
        return super.findArea() * getLength(); // Call the findArea method of the parent class
    }
    // Returns the surface area of the cylinder
    public double findArea(){
        return Math.PI * getRadius() * getRadius() * 2 + Math.PI * getRadius() * 2 * getLength();
    }
}
5. Understanding of java.lang.object class

The special declaration is the Object class under the java.lang package, because you may create an Object class with the same name
1. If we do not declare the parent class of a class first, this class inherits from the java.lang.Object class
2. All Java classes (except java.lang.Object class) inherit from java.lang.Object class directly or indirectly
3. All Java classes have the function declared by java.lang.Object class

5.2. Understanding of method rewriting (override/overwrite)

Override / overwrite: the method name and parameter list are the same, and only the method body is changed. The permission range can be the same or greater (except private), and the return value type is the same or greater
1. Override: after the subclass inherits from the parent class, it can override the methods with the same name and parameters in the parent class and execute its own methods
2. Application: after rewriting, when a subclass object is created and a method with the same name and parameter in the child parent class is called through the subclass object, the method of the subclass rewriting the parent class is actually executed (equivalent to the method defined by the subclass itself)
3. Application: Rewrite provisions:
Method declaration: permission modifier return value type method name (formal parameter list){
Method body
}
The Convention is commonly known as: the method in the subclass is called the overridden method, and the method in the parent class is called the overridden method
(1) The method name and parameter list of the method overridden by the subclass are the same as those of the method overridden by the parent class
(2) The permission modifier of the method overridden by the subclass is not less than the permission modifier of the method overridden by the parent class
Special case: a subclass cannot override a method declared as private permission in the parent class
(3) Return value type:
If the return value type of the method overridden by the parent class is void, the return value type of the method overridden by the child class can only be void
If the return value type of the method overridden by the parent class is type A, the return value type of the method overridden by the child class can be class A or a subclass of class A
If the return value type of the method overridden by the parent class is the basic data type (e.g. double), the return value type of the method overridden by the child class must be the same basic data type (it must also be double) (automatic type promotion is not the same as the child parent relationship)
(4) The exception type thrown by the method overridden by the subclass shall not be greater than the exception type thrown by the method overridden by the parent class (specific to exception handling)
========================================================================
Methods with the same name and parameters in the subclass and parent class are either declared as non static (only rewriting is considered) or static (must not be overridden), because (static) static methods cannot be overridden by subclasses and are loaded with the loading of classes
static can call this method directly through the class name

Non virtual methods: methods that cannot be overridden or overwritten refer to construction methods, static methods, private methods and final modified methods.
Virtual method: it refers to the method that can be rewritten. Generally, it refers to the instance method.
Virtual methods belong to objects, not classes

Interview question: distinguish between overloading and rewriting of methods

public class PersonTest {
    public static void main(String[] args) {
        Student s = new Student("Computer science and technology");
        s.eat();
        s.walk(10); // Obviously, the show method of the parent class is called in the walk method. If it is overridden, the show method of the child class will overwrite the parent class
        System.out.println("============");
        s.study();
        Person p1 = new Person();
        p1.eat(); // The object of the parent class calls the method of the parent class. If it still displays the method of the parent class, you can call it yourself if you define it yourself
    }
}
public class Person {
    String name;
    int age;
    public Person(){

    }
    public Person(String name, int age){
        this.name = name;
        this.age = age;
    }
    public void eat(){
        System.out.println("having dinner");
    }
    public void walk(int distance){
        System.out.println("What is the walking distance " + distance + " kilometre");
        show();
        eat();
    }
    // Methods declared as private permissions in a parent class cannot be overridden by subclasses
    private void show(){
        System.out.println("I am a human");
    }
    // The return value type of the method overridden by the parent class must be greater than or equal to the method overridden by the child class
    public Object info(){
        return null;
    }
    public double info1(){
        return 1.0;
    }
}
public class Student extends Person{
    String major;
    public Student(){

    }
    public Student(String major){
        this.major = major;
    }
    public void study(){
        System.out.println("Study major is: " + major);
    }
    // Overridden eat() in the parent class
    public void eat(){
        System.out.println("All students should eat nutritious food");
    }
// It is not rewritten, independent, and will not report errors
    public void show(){
        System.out.println("I am a student");
    }
    public String info(){
        return null;
    }
    // The basic data type returned by the subclass overriding method must be the same as that overridden by the parent class
    /*public int info1(){
        return 1;
    }*/
}

5.3. Four access modifiers

public class OrderTest {
    public static void main(String[] args) {
        Order order = new Order();
        order.orderDefault = 1;
        order.orderProtected = 2;
        order.orderPublic = 3;
        order.methodDefault();
        order.methodProtected();
        order.methodPublic();
        // Other classes in the same package cannot call private properties and methods in the Order class
        /*order.orderPrivate = 4;
        order.methodPrivate();*/
    }
}
public class Order {
    private int orderPrivate;
    int orderDefault;
    protected int orderProtected;
    public int orderPublic;
    private void methodPrivate(){
        orderPrivate = 1;
        orderDefault = 2;
        orderProtected = 3;
        orderPublic = 4;
    }
    void methodDefault(){
        orderPrivate = 1;
        orderDefault = 2;
        orderProtected = 3;
        orderPublic = 4;
    }
    protected void methodProtected(){
        orderPrivate = 1;
        orderDefault = 2;
        orderProtected = 3;
        orderPublic = 4;
    }
    public void methodPublic(){
        orderPrivate = 1;
        orderDefault = 2;
        orderProtected = 3;
        orderPublic = 4;
    }
}
==============================================
import com.oop.demo02.PermissionModifier.Order;

public class OrderTest {
    public static void main(String[] args) {
        // Embodied by creating objects
        Order order = new Order();
        order.orderPublic = 1;
        order.methodPublic();
        // Ordinary classes (non subclasses) under different packages should use the Order class. You cannot call properties and methods declared as private, default and protected permissions
        /*order.orderPrivate = 2;
        order.orderDefault = 3;
        order.orderProtected = 1;
        order.methodPrivate();
        order.methodDefault();
        order.methodProtected();*/
    }
    // By not creating an object representation, but the call (formal parameter) actually needs to create an object
    public void show(Order order){
        order.orderPublic = 1;
        order.methodPublic();
        // Ordinary classes (non subclasses) under different packages should use the Order class. You cannot call properties and methods declared as private, default and protected permissions
        /*order.orderPrivate = 2;
        order.orderDefault = 3;
        order.orderProtected = 1;
        order.methodPrivate();
        order.methodDefault();
        order.methodProtected();*/
    }
}
import com.oop.demo02.PermissionModifier.Order;

public class SubOrder extends Order {
    public void method(){
        // Because the parent class has been inherited, which is equivalent to calling its own properties and methods, it can be called without a new object
        // After inheritance, you can assign values directly, which is equivalent to inheritance declaring for you
        orderProtected = 1;
        orderPublic = 2;
        methodProtected();
        methodPublic();
        // In subclasses of different packages, you cannot call properties and methods that declare private and default permissions in the parent Order class
        /*orderDefault = 3;
        orderPrivate = 2;
        methodDefault();
        methodPrivate();*/
    }
}

5.4. Use of super keyword

1.super is understood as the parent class
2.super can be used to call (decorate): properties, methods, constructors, the parent class level of the call (proximity principle), and this is also the proximity principle
3. Use of super
3.1. You can explicitly call the attribute or method declared in the parent class in the method or constructor of the subclass by using "super. Attribute" or "super. Method". However, in general, it is customary to omit "super." (when the parent class has and the subclass has no attribute or method)
3.2. under special circumstances, when the attributes of the same name are defined in the child class and the parent class, if we want to call the properties declared in the parent class in the subclass, we must explicitly use the "super. attribute" method to indicate that the attributes declared in the parent class are invoked.
3.3. in special cases, when a child rewrites the method in the parent class, if it wants to call the rewritten method in the parent class in the subclass method, it must explicitly use the super. method to indicate that the method is rewritten in the parent class.
4.super call constructor
4.1. You can explicitly use "super (formal parameter list)" in the constructor of the subclass to call the specified constructor declared in the parent class
4.2. The use of "super (formal parameter list)" must be declared in the first line of the subclass constructor!
4.3. In the constructor of a class, "this" (which means calling other constructors overloaded in this class) or "super" (which means the constructor specified in the parent class) can only be selected from two and cannot appear at the same time
4.4. If there is no explicit declaration of "this" or "super" in the first line of the constructor, the null parameter constructor of the parent class: super() is called by default
4.5. There may be multiple constructors of a class. The first line of the constructor is either this (formal parameter list) or super (formal parameter list). You can only choose one from two. There can be no other cases
A class may have n constructors, and at least one constructor of the parent class called super(); at most n-1 constructors use this (formal parameter list), and the rest can only use super();

public class SuperTest {
    public static void main(String[] args) {
        Student s = new Student();
        s.show();
        s.study();
        Student s1 = new Student("tom", 21, "IT");
        s1.show();
        System.out.println("=================");
        Student s2 = new Student();

    }
}
public class Creature {
    int age = 1;
}
public class Person extends Creature {
    String name;
    int age;
    int id = 1001; // ID number
    public Person(){
        System.out.println("I'm everywhere!");
    }
    public Person(String name){
        this.name = name;
    }
    public Person(String name,int age){
        this(name);
        this.age = age;
    }
    public void eat(){
        System.out.println("people: having dinner");
    }
    public void walk(){
        System.out.println("people: sleep");
    }
}
public class Student extends Person{
    String major;
    int id = 1002; // At this time, the student id attribute has two IDS in memory. Unlike the method, the attribute will overwrite the parent class
    public Student(){
        super(); // The compiler executes the constructor of the parent class before executing the operation of the child class
    }
    public Student(String major){
        super(); // Each constructor in the subclass implicitly calls the null parameter constructor of the parent class by default,
        this.major = major;
    }
    // super use constructor
    public Student(String name, int age, String major){
        // (with inheritance right but without use right) inheritance is that a subclass inherits the properties and methods of the parent class, but calls the properties and methods decorated with private, and the subclass cannot access them directly
        super(name,age); // Call the constructor of the specified parameter of the parent class
        this.major = major;

    }
    @Override
    public void eat() {
        System.out.println("Students eat more nutritious things");
    }
    public void study(){
        System.out.println("Students learn knowledge");
        eat(); // The default is this.eat(), which calls the overridden method,
        super.eat(); // Call the method of the parent class
        walk(); // Call the method in the subclass that does not override the method in the parent class. Write this before the method, and super can usually be omitted. The difference is that this is found in the subclass first, and it is found in the parent class only when it is not found. Super directly looks in the parent class (including direct parent class and indirect parent class) until it is found
    }
    public void show(){
        // This: first look in the current Student class to see if there is a structure of this attribute. If it is not found in his own class, he will then look in the parent class
        // super: not found in the (current) subclass, go directly to the parent class
        System.out.println("name = " + this.name + ", age = " + super.age);
        System.out.println("id = " + id); // Omitted before id: this
        System.out.println("id = " + super.id);
    }
}

5.5. Subclass object instantiation process

The whole process of subclass object instantiation
If the parent class is not explicitly specified, the Object class is the parent class of the class. It is the default and does not need to be written explicitly
1. In terms of results: (inheritance)
After a subclass inherits from the parent class, it obtains the properties or methods declared by the parent class
For objects that create subclasses, the attributes declared in all parent classes (direct parent and indirect parent) will be loaded in heap space
2. In terms of process:
When you create a subclass object through the subclass constructor, you must directly or indirectly call the constructor of its parent class, and then call the constructor of the parent class of the parent class
Until the constructor of java.lang.Object class hollow parameter is called. Just because the home is in all the parent class structures, you can see that there are structures in the parent class in memory, and the child class objects can be considered for calling
Clear: Although the constructor of the parent class is called when creating a subclass object, an object has been created from beginning to end, that is, a subclass object of new, because an address is assigned in the heap value

Illustration:

  • Exercise: inherit & Super

public class AccountTest {
    public static void main(String[] args) {
        Account acct = new Account(1122, 20000, 0.045);
        acct.withdraw(30000);
        System.out.println("Account balance: " + acct.getBalance());
        acct.withdraw(2500);
        System.out.println("Account balance: " + acct.getBalance());
        acct.deposit(3000);
        System.out.println("Account balance: " + acct.getBalance());
        System.out.println("Monthly interest rate: " + (acct.getMonthInterest() * 100) + "%");
    }
}
public class Account {
    private int id; // account number
    protected double balance; // balance
    private double annualInterestRate; // Annual interest rate
    // Solution to the error of subclass constructor / class name: 1. Create an empty parameter constructor for the parent class 2. Create a specified constructor for the subclass
    public Account(int id, double balance, double annualInterestRate){
        super();
        this.id = id;
        this.balance = balance;
        this.annualInterestRate = annualInterestRate;
    }
    public void setId(int id){
        this.id = id;
    }
    public int getId(){
        return this.id;
    }
    public void setBalance(double balance){
        this.balance = balance;
    }
    public double getBalance(){
        return this.balance;
    }
    public void setAnnualInterestRate(double annualInterestRate){
        this.annualInterestRate = annualInterestRate;
    }
    public double getAnnualInterestRate(){
        return this.annualInterestRate;
    }
    // Return monthly interest rate
    public double getMonthInterest(){
        return this.annualInterestRate / 12;
    }
    // Withdraw money
    public void withdraw(double amount){
        if (balance >= amount){
            balance -= amount;
            return;
        }
        System.out.println("Sorry, your credit is running low");
    }
    // save money
    public void deposit(double amount){
        if (amount > 0){
            balance += amount;
        }
    }
}
public class CheckAccount extends Account{
    private double overdraft; // Overdraft limit

    public CheckAccount(int id, double balance, double annualInterestRate, double overdraft){
        super(id,balance,annualInterestRate);
        this.overdraft = overdraft;
    }
    public void setOverdraft(double overdraft){
        this.overdraft = overdraft;
    }
    public double getOverdraft(){
        return this.overdraft;
    }
    @Override
    public void withdraw(double amount) {
        // The balance is sufficient for consumption
        if (this.getBalance() >= amount){
            // Mode 1:
            // setBalance(getBalance() - amount);
            // Mode 2:
             super.withdraw(amount); // super. Properties / methods can call properties and methods of the parent class
            // Method 3: change the permission of balance to protected
            // balance = balance - amount;
            // Overdraft + balance sufficient for consumption
        }else if (overdraft >= amount - getBalance()){
            overdraft = overdraft - (amount - getBalance()); // Withdraw from the overdraft balance first
            // setBalance(0); / / clear the balance
            // or
            super.withdraw(getBalance());
        }else{
            System.out.println("Overdraft limit exceeded");
        }
    }
}
public class CheckAccountTest {
    public static void main(String[] args) {
        CheckAccount acct = new CheckAccount(1122, 20000, 0.045, 5000);
        acct.withdraw(5000);
        System.out.println("Account balance: " + acct.getBalance() + ", Overdraft balance: " + acct.getOverdraft());
        acct.withdraw(18000);
        System.out.println("Account balance: " + acct.getBalance() + ", Overdraft balance: " + acct.getOverdraft());
        acct.withdraw(3000);
        System.out.println("Account balance: " + acct.getBalance() + ", Overdraft balance: " + acct.getOverdraft());

    }
}

Posted by manmanman on Mon, 18 Oct 2021 15:39:24 -0700