Java summary 6: Object Oriented Programming

Posted by Poolie on Sun, 06 Feb 2022 08:05:07 +0100

โญ Classes and objects โญ ๏ธ

๐Ÿ“š First, let's look at a cat problem

Mrs. Zhang has two cats: one is Xiaobai, 3 years old, white. There is also a flower named Xiaohua, 10 years old, color. Please write a program to display the name, age and color of the kitten when the user enters the name of the kitten. If the kitten name entered by the user is wrong, it will show that Mrs. Zhang doesn't have the kitten

๐Ÿ“š Using existing technology to solve

Before, our technology was only:
โ˜• โ…ธ separate definition variables are solved
โ˜• ๏ฎ use array to solve

๐Ÿ“š Analysis of shortcomings solved by existing technology
โ˜• โ…ธ separate definition variable solution: it is not conducive to data management

     //Separate variables to solve = > not conducive to data management (you disassemble the information of a cat)
     //First cat information
     String cat1Name = "Xiaobai";
     int cat1Age = 3;
     String cat1Color = "white";
     //2nd cat information
     String cat2Name = "floret";
     int cat2Age = 10;
     String cat2Color = "Decor";

โ˜• โ…ธ use array to solve:
(1) The data type cannot be reflected;
(2) Information can only be obtained through [subscript], resulting in unclear correspondence between variable name and content;
(3) Can't reflect cat behavior.

//Array = = = > (1) data type cannot be reflected; (2) information can only be obtained through [subscript], resulting in unclear correspondence between variable name and content; (3) cat behavior cannot be reflected
//First cat information
String[] cat1 = {"Xiaobai", "3", "white"};
//2nd cat information
String[] cat2 = {"floret", "10", "Decor"};

๐Ÿ“š Optimization solution: introduce classes and objects (OOP)

The fundamental reason why java designers introduce classes and objects (OOP) is that the existing technology can not perfectly solve the new requirements

โ˜• ๏ผ› the code is as follows:

public class Object01 {
    //Write a main method
    public static void main(String[] args) {
        //Object oriented solution using OOP
        //Instantiate a cat [create a cat object]
        //1. Create a cat (cat object)
        //2. Cat cat1 = new Cat();  Assign the created cat to CAT1
        //3. cat1 is an object
        Cat cat1 = new Cat();
        cat1.name = "Xiaobai";
        cat1.age = 3;
        cat1.color = "white";
        cat1.weight = 10;
        //A second cat was created and assigned to cat2
        //cat2 is also an object (cat object)
        Cat cat2 = new Cat();
        cat2.name = "floret";
        cat2.age = 10;
        cat2.color = "Decor";
        cat2.weight = 20;
        //How do I access the properties of an object
        System.out.println("First cat information" + cat1.name
                + " " + cat1.age + " " + cat1.color + " " + cat1.weight);
        System.out.println("2nd cat information" + cat2.name
                + " " + cat2.age + " " + cat2.color + " " + cat2.weight);
    }
}
    //Use object-oriented method to solve the problem of keeping cats
//
//Define a cat - > custom data type
class Cat {
    //Attribute / member variable
    String name; //name
    int age; //Age
    String color; //colour
    double weight; //weight
//behavior
}

๐Ÿ“š A program is actually a world, which contains many things, which can be represented by objects, in which objects contain attributes and behaviors. (object [attribute, behavior)

๐Ÿ“š Schematic diagram of the relationship between class and object


explain:

  1. A class is a data type, such as Cat
  2. An object is a concrete instance,

๐Ÿ“š Differences and relations between classes and objects

โ˜• Class is abstract and conceptual, which represents a class of things, such as human beings, cats... That is, it is a data type;
โ˜• The object is concrete and practical, representing a specific thing, that is, an instance;
โ˜• A class is the template of an object. An object is an individual of a class, corresponding to an instance.

โญ โ’† object exists in memory (important!!!)

๐Ÿ“š Attribute / member variable / field

โ˜• โ…ธ from the concept or name: member variable = attribute = field (that is, member variable is used to represent attribute)
โ˜• The type of an object is also a basic type of data. For example, the int age of the cat class we defined earlier is the attribute.

๐Ÿ“š Precautions and details

โ˜• The definition syntax of attribute is the same as that of variable. Example: access modifier attribute type attribute name;
Among them, access modifiers: control the access range of attributes. There are four access modifiers: public, proctected, default and private, which will be described in detail later.
โ˜• The definition type of attribute can be any type, including basic type or reference type.
โ˜• If the attribute is not assigned, it has a default value, and the rules are consistent with the array. Specifically: int 0, short 0, byte 0, long 0, float 0.0,double 0.0, char \u0000, boolean false, String null.

public class Details {
    //Write a main method
    public static void main(String[] args) {
        //Create Person object
        //p1 is the object name (object reference)
        //The object space (data) created by new Person() is the real object
        Person p1 = new Person();
        //The default value of the property of the object complies with the array rules:
        //int 0๏ผŒshort 0, byte 0, long 0, float 0.0,double 0.0๏ผŒchar \u0000๏ผŒboolean false๏ผŒString null
        System.out.println("\n Current information about this person");
        System.out.println("age=" + p1.age + " name=" + p1.name + " sal=" + p1.sal + " isPass=" + p1.isPass) ;
    }
}
class Person {
    //Four attributes
    int age;
    String name;
    double sal;
    boolean isPass;
}

๐Ÿ“š How to create objects

๐Ÿ“’ Declaration before creation

Cat cat ; //Declare object cat
cat = new Cat(); //establish

๐Ÿ“’ Create directly

Cat cat = new Cat();

๐Ÿ“š How to access properties

Basic syntax: object name Attribute name;
Case demonstration assignment and output:

cat.name ;
cat.age;
cat.color;

โญ โ…ถ member method โญ ๏ธ

In some cases, we need to define member methods (Methods for short). For example, humans: in addition to some attributes (age, name...), we humans also have some behaviors, such as speaking, running... And doing arithmetic problems through learning. At this time, the member method can be used.

๐Ÿ“š Member quick start method

  1. Add the speak member method and output "I'm a good man";
  2. Add the cal01 member method to calculate the result from 1 +... + 1000;
  3. Add cal02 member method, which can receive a number N and calculate the result from 1 +... + n;
  4. Add the getSum member method to calculate the sum of two numbers.
public class Method01 {
    //Write a main method
    public static void main(String[] args) {
        //Method use
        //1. After the method is written, if it is not called (used), it will not be output
        //2. create the object first and then call the method.
        Person1 p1 = new Person1();
        p1.speak(); //Call method
        p1.cal01(); //Call the cal01 method
        p1.cal02(5); //Call the cal02 method and give n = 5
        p1.cal02(10); //Call the cal02 method and give n = 10
        //Call getSum method, and num1=10, num2=20
        //Assign the value returned by the method getSum to the variable returnRes
        int returnRes = p1.getSum(10, 20);
        System.out.println("getSum Method=" + returnRes);
    }
}
class Person1 {
    String name;
    int age;
    //Method (member method)
    //Add the speak member method and output "I'm a good man"
    //1. public means public
    //2. void: indicates that the method has no return value
    //3. Speak (): speak is the method name and () is the parameter list
    //4. {} method body, which can write the code we want to execute
    //5. System.out.println("I'm a good man"); Our method is to output a sentence
    public void speak() {
        System.out.println("I am a good man");
    }
    //Add the cal01 member method to calculate from 1 ++ 1000 results
    public void cal01() {
        //Cycle complete
        int res = 0;
        for(int i = 1; i <= 1000; i++) {
            res += i;
        }
        System.out.println("cal01 Method calculation results=" + res);
    }
    //Add the cal02 member method, which can receive a number N and calculate from 1 ++ Result of n
    //1. (int n) formal parameter list, indicating that there is currently a formal parameter n that can receive user input
    public void cal02(int n) {
        //Cycle complete
        int res = 0;
        for(int i = 1; i <= n; i++) {
            res += i;
        }
        System.out.println("cal02 Method calculation results=" + res);
    }
    //Add the getSum member method to calculate the sum of two numbers
    //1. The public representation method is public
    //2. int: indicates that an int value is returned after the method is executed
    //3. getSum method name
    //4. (int num1, int num2) formal parameter list, 2 formal parameters, which can receive two numbers passed in by the user
    //5. return res;  Indicates that the value of res is returned
    public int getSum(int num1, int num2) {
        int res = num1 + num2;
        return res;
    }
}

๐Ÿ“’ Output result:

I am a good man
cal01 Method calculation results=500500
cal02 Method calculation results=15
cal02 Method calculation results=55
getSum Method=30

๐Ÿ“š Benefits of membership approach

  1. Improve code reusability
  2. The implementation details can be encapsulated and then called by other users

๐Ÿ“š Definition of member method

Access modifier returns data type method name (formal parameter list)..) {//Method body
 sentence;
return Return value;
}

1. Formal parameter list: indicates the member method input cal(int n), getSum(int num1, int num2)
2. Return data type: indicates member method output, void indicates no return value
3. Method body: indicates a code block to implement a function
4. The return statement is not required.
5. Tips: combine with the schematic diagram of the previous question to understand

๐Ÿ“š Precautions and use details

๐Ÿ“’ Access modifier (used to control the scope of the method)
If you do not write the default access, [there are four types: public, protected, default and private], which will be described later.
๐Ÿ“’ Return data type

  1. A method can have at most one return value [think about how to return multiple results and return an array]
  2. The return type can be any type, including basic type or reference type (array, object)
  3. If the method requires a return data type, the last execution statement in the method body must be the return value; Moreover, the return value type must be the same as that of return
    Value types are consistent or compatible
  4. If the method is void, there can be no return statement in the method body, or just write return;

๐Ÿ“’ Method name
Follow the hump naming method. It's best to see the name and meaning and express the meaning of the function. For example, get the sum of two numbers - getSum, which is in accordance with the specification during development.
๐Ÿ“’ parameter list

  1. A method can have 0 parameters or multiple parameters separated by commas, such as getSum(int n1,int n2)
  2. The parameter type can be any type, including basic type or reference type, such as printArr(int[][] map)
  3. When calling a method with parameters, you must pass in parameters of the same type or compatible type corresponding to the parameter list! [getSum)4. Parameters during method definition are called formal parameters, which are referred to as formal parameters for short; parameters passed in during method call are called actual parameters, which are referred to as arguments for short. The types of arguments and formal parameters must be consistent or compatible, and the number and order must be consistent!
    ๐Ÿ“’ Method body
    Write specific statements to complete the function. It can be input, output, variable, operation, branch, loop and method call, but it can no longer define methods! That is: methods cannot be nested.
public class MethodDetail {
    public static void main(String[] args) {
        AA a = new AA();
        int[] res = a.getSumAndSub(1, 4);//Argument
        System.out.println("and=" + res[0]);
        System.out.println("difference=" + res[1]);
        //Details: when calling a method with parameters, you must pass in parameters of the same type or compatible type corresponding to the parameter list
        byte b1 = 1;
        byte b2 = 2;
        a.getSumAndSub(b1, b2);//byte -> int
        //a.getSumAndSub(1.1, 1.8);//double ->int(ร—)
        //Details: the types of arguments and formal parameters must be consistent or compatible, and the number and order must be consistent
        //a.getSumAndSub(100);// ×  Inconsistent number
        a.f3("tom", 10); //ok
        //a.f3(100, "jack"); //  The order of actual parameters and formal parameters is incorrect
    }
}
class AA {
    //Detail: methods cannot be nested
    public void f4() {
    //error
    // public void f5() {
    // }
    }
    public void f3(String str, int n) {
    }
    //1. A method can have at most one return value [think about how to return multiple results and return an array]
    public int[] getSumAndSub(int n1, int n2) {//Formal parameter
        int[] resArr = new int[2]; //
        resArr[0] = n1 + n2;
        resArr[1] = n1 - n2;
        return resArr;
    }
    //2. The return type can be any type, including basic type or reference type (array, object)
    // See getSumAndSub for details
    //3. If the method requires a return data type, the last execution statement in the method body must be the return value;
    //Moreover, the return value type must be consistent or compatible with the return value type
    public double f1() {
        double d1 = 1.1 * 3;
        int n = 100;
        return n; // int ->double
        //return d1; //ok? double -> int
    }
    //If the method is void, there can be no return statement in the method body, or just write return;
    //Tip: in actual work, our methods are to complete a function, so the method name must have a certain meaning
    //, it's better to see the name and know the meaning
    public void f2() {
        System.out.println("hello1");
        System.out.println("hello1");
        System.out.println("hello1");
        int n = 10;
        //return ;
    }
}

๐Ÿ“’ Method call details

  1. Method call in the same class: call directly. For example, print (parameter);
    Case demonstration: class A sayOk calls print()
  2. Class A method calls class B method across methods in class: it needs to be called through object name. For example, object name Method name (parameter); Case demonstration: Class B hi calls print()
  3. In particular, cross class method calls are related to method access modifiers.
public class MethodDetail02 {
    //Write a main method
    public static void main(String[] args) {
        A a = new A();
        //a.sayOk();
        a.m1();
    }
}
class A {
    //Method call in the same class: call directly
    public void print(int n) {
        System.out.println("print()Method called n=" + n);
    }
    public void sayOk() { //sayOk calls print (just call it directly)
        print(10);
        System.out.println("Continue execution sayOK()~~~");
    }
    //Class A method in cross class calls class B method: it needs to be called through object name
    public void m1() {
        //Create a B object, and then call the method
        System.out.println("m1() Method called");
        B b = new B();
        b.hi();
        System.out.println("m1() Continue execution:)");
    }
}
class B {
    public void hi() {
        System.out.println("B In class hi()Be executed");
    }
}

โญ Member method parameter transmission mechanism โญ ๏ธ

The parameter transmission mechanism of method is very important for our future programming. We must make it clear.

1. Parameter transmission mechanism of basic data type:
๐Ÿ“š Case:

public class MethodParameter01 {
    //Write a main method
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        //Create AA object name obj
        AA obj = new AA();
        obj.swap(a, b); //Call swap
        System.out.println("main method a=" + a + " b=" + b);//a=10 b=20
    }
}
class AA {
    public void swap(int a,int b){
        System.out.println("\na and b Value before exchange\na=" + a + "\tb=" + b);//a=10 b=20
        //Completed the exchange of a and b
        int tmp = a;
        a = b;
        b = tmp;
        System.out.println("\na and b Value after exchange\na=" + a + "\tb=" + b);//a=20 b=10
    }
}

๐Ÿ“š Focus on the following figure:

Conclusion:
The basic data type passes the value (value copy). Any change of formal parameters will not affect the actual parameters!
2. Parameter transfer mechanism of reference data type:

public class MethodParameter02 {
    //Write a main method
    public static void main(String[] args) {
         //test
         B b = new B();
         int[] arr = {1, 2, 3};
         b.test100(arr);//Call method
         System.out.println(" main of arr array ");
         //Traversal array
         for(int i = 0; i < arr.length; i++) {
         	System.out.print(arr[i] + "\t");
         }
         System.out.println();
    }
}
class Person {
    String name;
    int age;
}
class B {
    //You can receive an array and modify the array in the method to see if the original array changes
    public void test100(int[] arr) {
        arr[0] = 200;//Modify element
        //Traversal array
        System.out.println(" test100 of arr array ");
        for(int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + "\t");
        }
        System.out.println();
    }
}

๐Ÿ“š Operation results:

test100 of arr array 
200	2	3	
main of arr array 
200	2	3	

๐Ÿ“š Conclusion:
The reference type passes the address (the value is also passed, but the value is the address). You can affect the argument through formal parameters! (refer to the previous array here)
๐Ÿ“š Sketch Map:

public class MethodParameter02 {
    //Write a main method
    public static void main(String[] args) {
        B b = new B();
        Person p = new Person();
        p.name = "jack";
        p.age = 10;
        b.test200(p);
        System.out.println("main of p.age=" + p.age);//10000
    }
}
class Person {
    String name;
    int age;
}
class B {
    public void test200(Person p) {
        p.age = 10000; //Modify object properties
    }
}

๐Ÿ“š Operation results:

main of p.age=10000

๐Ÿ“š Sketch Map:

public class MethodParameter02 {
    //Write a main method
    public static void main(String[] args) {
        B b = new B();
        Person p = new Person();
        p.name = "jack";
        p.age = 10;
        b.test200(p);
        System.out.println("main of p.age=" + p.age);//10
    }
}
class Person {
    String name;
    int age;
}
class B {
    public void test200(Person p) {
        p = new Person();
        p.name = "tom";
        p.age = 99;
    }
}

๐Ÿ“š Operation results:

main of p.age=10

๐Ÿ“š Sketch Map:

๐Ÿ“š Conclusion:
The reference type passes the address (the value is also passed, but the value is the address). You can affect the argument through formal parameters!

๐Ÿ“š Thinking questions:

Consider the output value of the following code:

public class MethodParameter02 {
    //Write a main method
    public static void main(String[] args) {
        B b = new B();
        Person p = new Person();
        p.name = "jack";
        p.age = 10;
        b.test200(p);
        System.out.println("main of p.age=" + p.age);//10
    }
}
class Person {
    String name;
    int age;
}
class B {
    public void test200(Person p) {
        p=null;
    }
}

Many people's answer may be: abnormal, I can tell you, you did wrong!
The correct answer is: 10.

Why?
You can look at the following diagram first:
In the above diagram, the main stack starts with a P, which points to an object and calls b.test (P), which will open up a new space. P in the new space will also point to the same object. p=null means that P in the new space no longer points to the object, while P in the main method still points to the previous object, so the output of p.age is still 10.

โญ โ’ˆ the return type of member method is the application instance of reference type โญ ๏ธ

public class MethodExercise02 {
    //Write a main method
    public static void main(String[] args) {
        Person p = new Person();
        p.name = "milan";
        p.age = 100;
        //Create tools
        MyTools tools = new MyTools();
        Person p2 = tools.copyPerson(p);
        //Here, p and p2 are Person objects, but they are two independent objects with the same properties
        System.out.println("p Properties of age=" + p.age + " name=" + p.name);
        System.out.println("p2 Properties of age=" + p2.age + " name=" + p2.name);
       //Tip: you can compare with the same object to see if it is the same object
        System.out.println(p == p2);//false
    }
}
class Person {
    String name;
    int age;
}
class MyTools {
    //Write a method copyPerson, which can copy a Person object and return the copied object. Clone objects,
    //Note that the new object and the original object are two independent objects, but their properties are the same
    //
    //Ideas of compiling methods
    //1. Return type of method: Person
    //2. The name of the method is copyPerson
    //3. Formal parameter of method (Person p)
    //4. Method body, create a new object, copy the attribute, and then return
    public Person copyPerson(Person p) {
        //Create a new object
        Person p2 = new Person();
        p2.name = p.name; //Assign the name of the original object to P2 name
        p2.age = p.age; //Assign the age of the original object to P2 age
        return p2;
    }
}

๐Ÿ“š Sketch Map:

Topics: Java Back-end