Java Advanced (First Issue): static static modifier && design of tool class && inheritance && inherited access (member) + constructor access && use of this and super keywords && final keyword modification

Java basics:basics
Java basics:进阶


Java Advanced (First Issue)

1. static keyword

  • static Keyword: modifier, which can modify member variables and member methods

  • Characteristics:
    1. Shared by all objects of the class
    2.< a i=4> There is an additional calling method, which can be called directly through the class name (it is recommended to call using the class name)

    3. Loaded as the class is loaded, prior to object existence

1.1 Shared by all objects of the class
  • As follows, I modified the school member variable with static modifier
package com.liujintao.mystatic;
class Student {
    
    
    String name;
    int age;
    static String school;
}
  • Looking at my second reference in the code in the test class, I did not assign school, but I can still print (this is sharing)
package com.liujintao.mystatic;
/*
    static 关键字:修饰符,可以修饰成员变量和成员方法

    特点:
            1. 被类的所有对象所共享
            2. 多了一种调用方式,可以通过类名直接调用(推荐使用类名调用)
            3. 随着类的加载而加载,优先于对象存在
 */



public class StaticDemo1 {
    
    
    public static void main(String[] args) {
    
    
        Student stu1 = new Student();
        stu1.name = "张三";
        stu1.age = 23;
        stu1.school = "人工智能竞赛";
        System.out.println(stu1.name + "---" + stu1.age + "---" + stu1.school);


        System.out.println("---------------------------");
        Student stu2 = new Student();
        stu2.name = "李四";
        stu2.age = 24;
        System.out.println(stu2.name + "---" + stu2.age + "---" + stu2.school);


    }

}

Zhang San—23—Artificial Intelligence Competition

Li Si-24-Artificial Intelligence Competition

Just because school is modified by static, it can still be shared and used.

        Student stu3= new Student();
        System.out.println(stu3.name + "---" + stu3.age + "---" + stu3.school);

null—0—artificial intelligence competition

  • The object is created here without assigning a value, but I made the school static so that it can share the data of all objects in the class. If the first two are not modified, the default values ​​will be printed.
1.2. You can call it directly using the class name (recommended)
System.out.println(Student.school);

artificial intelligence competition

  • Can be called directly using the class name
1.3 Prioritize the existence of objects
System.out.println(Student.school);
Student stu1 = new Student();
  • If this code method is placed above the constructor, you can access the member variables in the class.

null

Because there is no initial value, the result here is the default value.

1.4 static static memory map

Insert image description here

  • Static members in a class are loaded when the class is loaded. The object is not created, our static members already exist.

As long as the class is loaded by bytecode! The statically modified member will create a class static member variable area in the heap space. Specially used to store static method data.

1.5 Application scenarios
  • Member variables: When you want the data to be shared, add the static modifier
  • Member methods: often used in tool classes

2. Tools

2.1 About the use of static methods
1. 成员方法什么时候加入 static 
    		- 常用于制作工具类
2. 工具类: 不是描述的事物的,而是帮我们完成一些事情(打工)
3. 如果发现一个类中,所有的方法,全是 static 所修饰
    	- 那么我们就要手动的修饰类的 构造方法
    	- 目的:为了不让其他类,在创建对象

Create a utility class:

package com.liujintao.tools;

public class ArrayTools {
    
    
    // 将构造方法私有化(因为可以通过类名访问我里面的方法了,不需要再开辟空间了)
    private  ArrayTools(){
    
    };
    /**
     * 求数组最大值方法
     */
    public static int getMax (int[] arr) {
    
    
        int max = arr[0];
        for (int i = 0; i < arr.length; i++) {
    
    
            if (max < arr[i]) {
    
    
                max = arr[i];
            }
        }
        return max;
    }

    /**
     * 求数组最小值方法
     */
    public static int getMin (int[] arr) {
    
    
        int min = arr[0];
        for (int i = 0; i < arr.length; i++) {
    
    
            if (min > arr[i]) {
    
    
                min = arr[i];
            }
        }
        return min;
    }

    /**
     *  遍历数组方法
     */
    public static void forInput (int[] arr) {
    
    
        System.out.print("[");
        for (int i = 0; i < arr.length - 1; i++) {
    
    
            System.out.print(arr[i] + ",");
        }
        System.out.print(arr[arr.length - 1] + "]");
    }
}

Test using tool class methods

package com.liujintao.tools;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = {
    
    11, 22, 33};
        // 静态方法直接还用类名访问调用里面的方法(不需要构造器创建对象了)
        System.out.println(ArrayTools.getMax(arr));
        System.out.println(ArrayTools.getMin(arr));
        ArrayTools.forInput(arr);
    }
}

Output result:

33
11
[11,22,33]

ask:

Why is there no need to create an instance object here?

answer:

The static modified member method becomes a static class (you can directly access the methods inside). There is no need to use the constructor to create the object and then operate it. Remember to privatize the constructor method in the tool class to avoid waste.

2.2. Notes on static static:
  • In static methods, only static members can be accessed (direct access)
  • The this keyword is not allowed in static
package com.liujintao.mystatic;
/*
    演示静态静态类在不通过实例的时候,我们只能访问到静态的成员变量和方法
 */
public class StaticDemo2 {
    
    
    static String name= "张三";
    static int age = 18;
    char gender = '男';

    private StaticDemo2(){
    
    }; // 将构造方法私有化

    /**
     *  创建一个静态方法
     */

    public static void Method1 () {
    
    
        System.out.println("我是静态方法");
    }

    /**
     *  创建一个非静态的成员方法
     */

    public void Method2 () {
    
    
        System.out.println("我是一个非静态的成员方法");
    }


    // 静态的主方法
    public static void main(String[] args) {
    
    
        // 1. 不使用构造器构造实例(直接访问)
        System.out.println(name);
        System.out.println(age);
        Method1();


        // 2. 访问非静态的成员(报错),因为类都没被加载使用
        // System.out.println(gender); 报错(因为非静态的,需要构造对象使用)
        // Method2(); 报错


        /**
         * 解决方案
         */
        StaticDemo2 sd = new StaticDemo2();
        System.out.println(sd.gender);
        sd.Method2();
    }
}

  • This cannot be used because the object has not been created by the class. Can you tell me how to use this? So it cannot be used.

3. Inheritance (extends)

  • Inheritance: Create a relationship between classes (child-parent class relationship), and subclasses can use it directly父类中非私有的成员.
3.1 Inherited formats

Inherited format:

  • Format:public class 子类名 extends 父类名{}
  • demonstration:public class zi extends fu {}
  • fu: is the parent class, also called base class and superset
  • zi: It is a subclass, derived class

Details of creating the class:

  1. Multiple classes can be written in one .java file
  2. Ensure that there is a horizontal relationship between classes
  3. Only one of them can be modified by public
package com.liujintao.mextends;

public class ExtendsDemo1 {
    
    
    public static void main(String[] LiuJinTao) {
    
    
        // 子类访问非私有化的父类成员
        Zi1 z1 = new Zi1();
        System.out.println(z1.name = "张三");
        System.out.println(z1.age = 23);
        System.out.println(z1.gender = '男');

        // 子类访问父类私有化的成员方法 (get   和   set)
        Zi2 z2 = new Zi2();
        z2.setScore(99);
        z2.setPrice(999.99);
        System.out.println(z2.getScore() + "---" + z2.getPrice());
    }
}

// 父类
class Fu  {
    
    
    String name;
    int age;
    char gender;
    private double score;
    private double price;

    // 通过JavaBean中的get和set方法实现子类访问父类私有化的成员


    public double getScore() {
    
    
        return score;
    }

    public void setScore(double score) {
    
    
        this.score = score;
    }

    public double getPrice() {
    
    
        return price;
    }

    public void setPrice(double price) {
    
    
        this.price = price;
    }
}

// 子类继承父类 Fu
class Zi1 extends Fu {
    
    

}

// 子类继承父类 Fu
class Zi2 extends Fu {
    
    

}

Output example:

张三
23
99.0---999.99
3.2 When to use inheritance?
  • When there is common (commonality) content between classes, and the products that are mutually reasonable (such as managers and programmers) all belong to employees, then employees can be set as the parent class. . To achieve code optimization

Project manager: name, job number, salary

Programmer: name, job number, salary

  • There are commonalities between the two of them, so we can extract them and put them in the parent class, so that they can inherit the parent class.

4. Inheritance - member variables (access characteristics)

4.1 The member variables in inheritance have duplicate names. How to deal with the data?

If there are member variables with the same name in the character class, they will still be used according to the proximity principle.

  • So what should I do if I want to use member variables with the same name in the parent class?
package com.liujintao.mextends;

import java.sql.SQLOutput;

public class ExtendsDemo2 {
    
    
    public static void main(String[] args) {
    
    
        ZiClass zi = new ZiClass();
        zi.method();
    }

}

class FuClass {
    
    
    int num = 10;

}

class ZiClass extends FuClass {
    
    
    int num = 20;
    public void method () {
    
    
        System.out.println(num);    // 就近原则 : 20
        System.out.println(super.num);  // 访问父类 : 10
    }
}

  • Super is used above to access the member variables of the parent class, just like this can access all members of this class.
4.2 The use of this and super when accessing member variables
  • this: call members of this class
  • super: call parent class members
class FuClass {
    
    
    int num = 10;

}

class ZiClass extends FuClass {
    
    
    int num = 20;
    public void method () {
    
    
        int num = 30;
        System.out.println(num);    // 就近原则 : 30
        System.out.println(super.num);  // 访问父类 : 10
        System.out.println(this.num);   // 调用本类成员:20
    }
}

The above code implements using different keywords to access member variables in different class scopes.

4.3 What to do if the same member method appears in inheritance?

In the parent class, there is a method with exactly the same method declaration (method name, parameters, return value)

  • When creating a subcolumn object and calling a method, the method logic of the subclass will be used first.
  • It is very similar to the proximity principle, but it is actually a subclass method that overrides the parent class method.
public Text {
    
    
   	Zi z = new Zi();
    z.show() // 我是子类方法
}

// 父类
class Fu {
    
    
    public void show() {
    
    
       	System.out.println("我是父类方法");
    }
}

// 子类
class Zi {
    
    
    public void show () {
    
    
        System.out.println("我是子类方法");
    }
}
  • The above code is that the subclass inherits the parent class, and at the same time adds member methods, and then ultimately accesses the methods of the subclass. This is not the principle of proximity, but method rewriting (method rewriting will be explained in detail below)

5. Method rewriting

5.1 Method rewriting and method overloading

Method overloading (Overload): In the same class, the method name is the same but the parameters are different, regardless of the return value → Different parameters: different types, different numbers, and different orders

Method override (Override): In the child and parent classes, there are methods with exactly the same method declaration (method name, parameters, return value).

  • To identify whether it is method overriding, use @Override directly on the method. If no error is reported, it proves that it is method overriding, otherwise it is not.
  • Usage scenario: When a subclass needs a parent class method, but feels that there are too few things in the parent class method, and I want to add or modify it, then I can use method rewriting at this time.
5.2 Code examples
package com.liujintao.mextends;

public class ExtendesDemo3 {
    
    
    public static void main(String[] LiuJinTao) {
    
    
        Son s = new Son();
        s.classHandle();
    }
}


class Fathod {
    
    
    public void classHandle() {
    
    
        System.out.println("起床");
        System.out.println("吃饭");
        System.out.println("睡觉");
    }
}

class Son extends Fathod {
    
    
    @Override
    public void classHandle() {
    
    
        // 使用super关键字指定父类的方法,如果我们重写这个方法不需要(可以删除)
        super.classHandle();
        // 下面我们就可以重写方法(这里添加逻辑)
        System.out.println("我是方法重写");
        System.out.println("但是我保留了父类方法中的逻辑");
    }
}

  • When the subclass uses the method of the parent class, it is rewritten. At the same time, it retains the logic of the parent class.

Output example:

起床
吃饭
睡觉
我是方法重写
但是我保留了父类方法中的逻辑
5.3 Things to note when rewriting methods
  • Private methods in parent classes cannot be overridden
  • The subclass overrides the parent class method, and the access permission must be greater than or equal to the parent class (if it is less, an error will be reported)
5.4 Characteristics of inheritance in java

Insert image description here

Either inherit one, or inherit at multiple levels, and you cannot inherit multiple at the same time.

Code implementation to implement multi-level inheritance:

package com.liujintao.mextends;

public class ExtendxDemo04 {
    
    
    public static void main(String[] LiuJinTao) {
    
    
        C c = new C();
        c.methodC();    // 调用本类方法
        c.methodB();    // 调用继承的父级类方法
        c.methodA();    // 调用父级继承的爷爷类方法
    }
}

class A {
    
    
    public void methodA () {
    
    
        System.out.println("我是爷爷辈");
    }
}


class B extends A {
    
    
    public void methodB () {
    
    
        System.out.println("我是父亲辈");
    }
}

class C extends B {
    
    
    public void methodC () {
    
    
        System.out.println("我是儿子辈");
    }
}



  • The above is how to write hierarchical inheritance classes (note that method rewriting is not used here)

Output example:

我是儿子辈
我是父亲辈
我是爷爷辈

6. Characteristics of member access in inheritance - constructor method

6.1 Answers to questions about inheritance

Question 1: Can the constructor be inherited?

Answer 2: The constructor cannot be inherited because the constructor can only have the same name as the class.

Question 2: Does the subclass need to initialize the parent class before creating it?

Answer 2: Yes, because when creating a subclass, the parent class may need to be involved.

Question 3: How does the subclass complete the initialization of the parent class?

Answer 3: The subclass only needs to have access to the constructor of the parent class to achieve this.

Question 4: What method is used for object initialization?

Answer 4: Construction method

Jump to the conclusion:

  • In all construction methods, a sentence is hidden by default super();
  • Through this code, you can access the empty parameter constructor in the parent class.
6.1 super() accesses the parent class constructor
  • Except for the Object class, in the first line of code of all construction methods, there is a silent sentence super(); through this code, the empty parameter construction method of the parent class is accessed.

detail:

  • All classes in Java directly or indirectly inherit the Object class.

package com.liujintao.mextends.construction;

public class constructionDemo {
    
    
    public static void main (String[] LiuJinTao) {
    
    
        Zi zi = new Zi();
        Zi z2 = new Zi(520);
    }
}

class Fu {
    
    
    public Fu () {
    
    
        super(); 	// 指向的是上级,没有继承则为:Object
        System.out.println("我是父类空参构造器");
    }

    public Fu (int num) {
    
    
        System.out.println("我是父类带参构造器");
    }
}


class Zi extends Fu{
    
    
    
    public Zi () {
    
    
        super();
        System.out.println("我是子类空参构造器");
    }

    public Zi (int num) {
    
    
        super();
        System.out.println("我是子类带参构造器");
    }
}



  • The super(); method is constructed with access to the parent's empty parameters.

Output example:

我是父类空参构造器
我是子类空参构造器
我是父类空参构造器
我是子类带参构造器

7. Inheritance construct access usage exercises

7.1 Exercises

Create a parent class

package com.liujintao.test;

public class Person {
    
    
    private String name;
    private int age;

    public Person() {
    
    
    }

    public Person(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
    
    
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
    
    
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
    
    
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
    
    
        this.age = age;
    }

}

Create the first subclass:

package com.liujintao.test;

public class Teachar extends Person {
    
    
    // 两个构造器
    public Teachar () {
    
    }

    public Teachar (String name, int age) {
    
    
        super(name, age);
    }
    public void teach () {
    
    
        System.out.println("姓名为" + super.getName() + ",年龄为" + super.getAge() + "岁的老师正在讲课");
    }
}

Create a second subclass:

package com.liujintao.test;

public class Student extends Person {
    
    
    private double score;


    public Student () {
    
    

    }
    public Student (String name, int age, double score) {
    
    
        super(name, age);
        this.score = score;
    }


    public void study () {
    
    
        System.out.println("姓名为" + super.getName() + ",年龄为" + super.getAge() + "岁,成绩为" + score + "分的学生,正在学习");
    }
}

The test class operates two subclasses:

package com.liujintao.test;

public class Test {
    
    
    public static void main(String[] LiuJinTao) {
    
    
        Teachar th = new Teachar("张三", 24);
        Student stu = new Student("李四", 18, 99.9);
        th.teach();
        stu.study();
    }

}

Output example:

姓名为张三,年龄为24岁的老师正在讲课
姓名为李四,年龄为18岁,成绩为99.9分的学生,正在学习
  • The key point is the use of super(); the method inherits the parent class constructor to implement data storage. Then use the super operation member method in the parent class to process the data logic.
7.2 Memory map

Insert image description here

  • There will be a super area in the heap memory class, which is dedicated to storing the data of the parent class.

8. Comprehensive cases of inheritance

need:

Insert image description here


code show as below:

Test class code:

package com.liujintao.test2;

/**
 * 我是测试类
 */
public class Test {
    
    
    public static void main(String[] LiuJinTao) {
    
    
        Coder code = new Coder("张三", 23, 15000);
        Manager mg = new Manager("李四", 24, 18000, 5000);
        // 调用两个子类的的方法
        code.work();
        mg.work();
    }
}

Parent class code:

package com.liujintao.test2;

import com.liujintao.mextends.A;

/**
 * 我是一个员工类
 */
public class Emeployee {
    
    
    private String name;
    private int age;
    private int wage;


    public Emeployee() {
    
    
    }

    public Emeployee(String name, int age, int wage) {
    
    
        this.name = name;
        this.age = age;
        this.wage = wage;
    }

    /**
     * 方法类
     */
    public void work () {
    
    
        System.out.println("姓名为" + name + ",年龄为" + age + ",工资为" + wage + "的程序员正在编写代码");
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
    
    
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
    
    
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
    
    
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
    
    
        this.age = age;
    }

    A

    /**
     * 获取
     * @return wage
     */
    public int getWage() {
    
    
        return wage;
    }

    /**
     * 设置
     * @param wage
     */
    public void setWage(int wage) {
    
    
        this.wage = wage;
    }

}

Subclass 1 code:

package com.liujintao.test2;

/**
 * 我是程序员类
 */
public class Coder extends Emeployee {
    
    
    // 通过构造器获取数据
    public Coder (String name, int age, int wage) {
    
    
        // 通过 super 操作父级的构造器,初始化父级类中的成员变量
        super(name, age, wage);
    };
}

Subclass 2 code:

package com.liujintao.test2;

/**
 * 我是项目经理类
 */
public class Manager extends Emeployee {
    
    
    // 奖金
    private int bonus;

    // 该构造方法接受到实例传递过来的数据,然后通过构造器里面的super方法操作父级的构造器,从而实现初始化数据
    public Manager (String name, int age, int wage, int bonus) {
    
    
        super(name, age, wage);
        // 多出来的变量我们自己处理就好了
        this.bonus = bonus;
    }

    public void work () {
    
    
        // 使用方法重写(并且不继承父级该方法的原有属性)
        System.out.println("姓名为" + super.getName() + ",年龄为" + super.getAge() + ",工资为" + super.getWage() + "奖金为" + bonus + "的项目经理正在分配任务...");
    }
}

Output example:

姓名为张三,年龄为23,工资为15000的程序员正在编写代码
姓名为李四,年龄为24,工资为18000奖金为5000的项目经理正在分配任务...

9. this and super

  • this: represents a reference to an object of this class
  • super: represents the identifier of the parent class storage space
Keywords Access member variables Access member methods access constructor
this this.Member variable of this class this.Member method of this class(); this(); this(...);Construction method of this class
super super.parent class member variable super.parent class member method super(); super(…); parent class constructor

Note: both this() and super() are competing for the first line of the constructor, so they cannot coexist.

10. Introduction to the final keyword

final: The meaning of the keyword (final), which can be used to modify (methods, classes, variables)

  • final: Characteristics of modification:

    • Table name: This method is final and cannot be overridden.
    • Indicates that this class is the final class and cannot be inherited.
    • Indicates that the variable is a constant and cannot be assigned a value again.
  • final naming convention:

  • A word in all caps: max → MAX

  • Multiple words are all capitalized and separated by _: maxValue → MAX_VALUE

Additional details on final modified variables:

  • The variable is a basic data type: the final modification means that the data value of the basic type cannot be changed.
  • The variable is a reference data type: final modification means that the address value of the reference data type cannot be changed, but the content in the address can be changed.
  • If the member variable is final modified, it needs to be copied before the end of the constructor.

The knowledge points you need to master in this issue.

Insert image description here

Java advancement has begun (updating...) Come on

Guess you like

Origin blog.csdn.net/Forever_Hopeful/article/details/134620239