Java --- object and polymorphism

JAVA objects and polymorphism (object-oriented)

Object oriented Foundation

A class is equivalent to a template, and an object is an entity created according to the template. A class is an abstract data type, not a real concrete existence. Class properties: member variables and member methods. You can call member methods to make the class perform some operations.

For example: Scanner sc= new Scanner(System.in);
             String str = sc.nextLine();
             System.out.println("you entered:" + str);
              sc.close();

All objects need to be created through the new keyword. Variable types are divided into basic type variables and reference type variables. A reference type variable represents an object, and a basic type variable represents a value.

Basic structure of class

The created class file name should be consistent with the class name.

Member variable

Member variables are also called member properties. We can access and modify these variables through the objects created by the class.

public class Test {
    int age;
    String name;
}

public static void main(String[] args) {
    Test test = new Test();
    test.name = "Maple Leaf Xiaoxiao";
    System.out.println(test.name);
}

Member method

A method is a collection of statements that exist to accomplish something. When you finish something, you can have results, or you can do it without returning results.

Definition and use of methods

Define a main method:

public static void main(String[] args) {
  //Body
}

Define any method:

[return type] Method name([parameter]){
  //Method body
  return result;
}
  1. Return value type: it can be reference type, basic type or void, indicating that there is no return value
  2. Method name: consistent with the rules of identifier. Like variables, it starts with lowercase letters!
  3. Parameters: for example, if the method needs to calculate the sum of two numbers, we need to tell the method what the two numbers are, and then they can be passed into the method as parameters
  4. Method body: specific things to do
  5. Result: the result of method execution is returned through return (if the return type is void, return can be omitted)

  1. Return , can also be used to end the whole method in advance. No matter where the program is executed or where return is located, the method will end immediately!
  2. If the parameter passed into the method is a basic type, the value of the parameter will be copied when calling the method. The parameter variable in the method is not the variable we passed in!
  3. The parameter of the method passed in. If it is a reference type, the reference of the object will still be passed in.
  4. Methods can call each other and methods can call themselves (recursion)

Overloading of methods

A class can contain multiple methods with the same name, but the required formal parameters are different.
public class Test {
    int a(){   //Original method
       return 1;
    }

    int a(int i){  //ok, the formal parameters are different
        return i;
    }
    
    void a(byte i){  //ok, the return type and formal parameters are different
        
    }
    
    void a(){  //Error, only the return value type name is different, and cannot be overloaded
        
    }
}

Construction method

Constructor (constructor) has no return value.

//Decompile result
package com.test;

public class Test {
    public Test() {    //Even if you don't write anything, you also bring a parameterless constructor, which is hidden by default
    }
}

We can manually specify the parameterized structure. In case of name conflict, we need to use the keyword this

public class Student {
    String name;

    Student(String name){   //If the formal parameter conflicts with the class member variable, Java will give priority to the variable defined by the formal parameter!
        this.name = name;  //this represents the current object by referring to the current object attribute
    }
}

//Right click idea to generate it quickly!

Note: this can only be used to refer to the content of the current object. Therefore, this can only be used for the part owned by the object, that is, this can only be used in the member methods of the class, and this keyword cannot be used in static methods.

Static variables and static methods

Static variables and static methods are the attributes of a class (static classes and static code blocks will be mentioned later), which can also be understood as the content shared by all objects. We use the static keyword to declare a variable or method static. Once declared static, all objects created through this class operate on the same target, that is, no matter how many objects there are, there is only one static variable or method. Then, if an object changes the value of a static variable, other objects read the changed value.

Class loading mechanism

Classes are not all loaded at the beginning, but only when needed. If classes are loaded:

  1. Access the static variable of the class or assign a value to the static variable
  2. new creates an instance of the class (loading implicitly)
  3. Calling a static method of a class
  4. Subclass initialization
  5. Other situations will be introduced when talking about reflection

All content marked as static will be allocated when the class is just loaded, rather than when the object is created, so the static content will be loaded before the first object is initialized.

Definition and assignment are two stages, and the default value will be used when defining. After the definition, if an assignment statement is found, the assignment will be carried out again. At this time, the static method is called, so the static method will be loaded first. When the static method is called, a will be obtained. At this time, a is just defined, so it is still the initial value, and finally 0 will be obtained.

public class Student {
    static int a = test();

    static int test(){
        return a;
    }

    public static void main(String[] args) {
        System.out.println(Student.a);
    }
}

Code block and static code block

The code block is executed when the object is created, which is also the content of the class, but it is executed before the construction method is executed, and it is executed only once every time an object is created.

String and StringBuilder classes

String class is a special class. It is the only class that overloads operators in Java. String splicing may be optimized by the compiler into StringBuilder to reduce object creation. StringBuilder is also a class, but it can store variable length strings!.

Package and access control

Packages are actually things used to distinguish classification positions, and can also be used to classify our classes. (package xxx);

package com.test;

public class Test{
  
}

Call the class in other packages: import

import com.test.*;

. * represents all calls in the package.

access control

Java supports the protection of class attribute access, that is, it does not want external classes to access properties or methods in the class, and only internal calls are allowed. In this case, we need to use the permission controller. (private)

Permission controllers can be declared in front of methods, member variables and classes. Once private is declared, it can only be accessed inside the class!

public class Student {
    private int a = 10;   //It has private access rights and can only be accessed inside the class
}

public static void main(String[] args) {
    Student s = new Student();
    System.out.println(s.a);  //Is it still accessible?
}

Array type

Sometimes we need to use multiple data, and it is troublesome to define one by one. At this time, we need to use the array. An array can represent a group of contents of any same type. Each data stored in it is called an element of the array. The subscript of the array starts from 0, that is, the index of the first element is 0.

One dimensional array

In a one-dimensional array, the elements are arranged in order (linear).

type[] Variable name = new type[Array size];
Type variable name n = new type[Array size];  //Support C language style, but not recommended!

type[] Variable name = new type[]{...};  //Static initialization (specify value and size directly)
type[] Variable name = {...};   //Same as above, but can only be assigned at the time of definition

Each element of the created array has a default value, which can be accessed through subscript:

int[] arr = new int[10];
arr[0] = 626;
System.out.println(arr[0]);
System.out.println(arr[1]);

Get array length:

int[] arr = new int[]{1, 2, 3};
System.out.println(arr.length);  //Print the value of the length member variable

Traversal of array

Traditional for loop

int[] arr = new int[]{1, 2, 3};
for (int i = 0; i < arr.length; i++) {
   System.out.println(arr[i]);
}

foreach

int[] arr = new int[]{1, 2, 3};
for (int i : arr) {
    System.out.println(i);
}

foreach is an enhanced for loop, which makes the code more concise, and we can get every number in the array directly.

Two dimensional array

In fact, a two-dimensional array is an array that stores an array. Each element stores a reference to an array.

//Three rows and two columns
int[][] arr = { {1, 2},
                {3, 4},
                {5, 6}};
System.out.println(arr[2][1]);

The traversal of two-dimensional arrays is the same as that of one-dimensional arrays, except that nested loops are required.

int[][] arr = new int[][]{ {1, 2},
                           {3, 4},
                           {5, 6}};
for (int i = 0; i < 3; i++) {
     for (int j = 0; j < 2; j++) {
          System.out.println(arr[i][j]);
     }
}

Multidimensional array

There are not only two-dimensional arrays, but also three-dimensional arrays, that is, arrays that store arrays. The principle is the same as that of two-dimensional arrays, which can be accessed level by level.

Variable length parameter

Variable length parameter is actually an application of array. We can specify the formal parameter of the method as a variable length parameter. It is required that 0 or more arguments can be filled in dynamically according to the situation, rather than a fixed number.

public static void main(String[] args) {
     test("AAA", "BBB", "CCC");    //Variable length, and finally will be automatically encapsulated into an array
}
    
private static void test(String... test){
     System.out.println(test[0]);    //In fact, the parameter is an array
}

Because it is an array, only one type of variable length parameter can be used, and the variable length parameter can only be placed in the last bit.

Keywords: Java JavaSE IDEA

Added by parse-error on Wed, 23 Feb 2022 18:25:33 +0200