The latest series of basic Java courses--Day07-object-oriented features

​ Author homepage: Programming Compass

About the author: High-quality creator in the Java field, CSDN blog expert
, CSDN content partner, invited author of Nuggets, Alibaba Cloud blog expert, 51CTO invited author, many years of architect design experience, resident lecturer of Tencent classroom

Main content: Java project, Python project, front-end project, artificial intelligence and big data, resume template, learning materials, interview question bank, technical mutual assistance

Favorites, likes, don't get lost, it's good to follow the author

Get the source code at the end of the article

Dear students, in the next two days of class, we will continue to study object-oriented related courses. Object-oriented is the core routine of writing Java programs. If you don't understand object-oriented, it is equivalent to learning Java for nothing. Therefore, in the next two days, all students also need to overcome many difficulties and study hard.

We said earlier that the core routine of object-oriented is: design objects to process data and solve problems. If you learn the advanced object-oriented course well, the objects you design will be more useful.

Before formally studying object-oriented advanced courses, I would like to give you some suggestions for learning. At present, the knowledge points of the advanced object-oriented part we are learning are like screws one by one. During the learning process, you may not know where these screws are used and what problems they solve. Only after studying all these contents can we know that these screws can be used to build airplanes, aircraft carriers, and rockets.

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-DIrHEUqU-1690168860638)(assets/1663976726206.png)]

Therefore, at this stage, in the learning process, we mainly focus on the following points. After the entire basic course is completed, I will slowly feel where it is used.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-2M38VJnu-1690168860641)(assets/1663976889900.png)]

1. Private and public members of a class

1.1 Private members

If the private access control symbol private is added before the member declaration of a class, the member can only be accessed and modified by the class itself, but not by other classes (including subclasses of the class). The purpose of the highest level of data protection has been achieved.

Example:

public class demo{
    
    

   private int age = 100;
   
   public int getAge(){
    
    
      return age;  //可以在类的内部方法中使用private成员,但外部类不可以
   }

}

So how does an external class access the internal private members of a class? For example, in the previous example, the private Chengzhong attribute can be accessed through the public Chengzhong method. If a method is declared private, it cannot be called by external classes.

1.2 Public members

Adding the public access control symbol public before the member declaration of a class means that the member can be accessed by other classes. It causes a decrease in security and data encapsulation, so the use of this member is generally reduced.

public class Demo{
    
    

   private int age = 100;
   public String name = "sisa";
    
   public int getAge(){
    
    
      return age;  //可以在类的内部方法中使用private成员,但外部类不可以
   }

}

In the above example: the name attribute is public, and the getAge() method is public and can be accessed by external classes

public class Demo01{
    
    
   public static void main(String[] args){
    
    
        Demo demo = new Demo();
        demo.name = "sisa2023";
        int age = demo.getAge();
   }

}

1.3 Default access control characters

If no access control character is added in front of the class member, the member has the default access control characteristics.
The default access control means that this member can only be accessed and called by classes in the same package (class library). If a subclass is located in a different package from the parent class, the subclass cannot access the default access control members in the parent class, which means that any class in other packages cannot access the default access control members.
Similarly, for classes, if a class has no access control character, it means it has default access control characteristics.

Two, static

Next, let's learn a keyword static that is very common in object-oriented programming.

Static is read as static and can be used to modify member variables and member methods. Let's first learn about static modification of member variables.

1.1 Static modification of member variables

Member variables in Java are divided into two types according to whether they are statically modified: class variables and instance variables . The difference between them is shown in the figure below:

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-yczvC2xQ-1690168860643)(assets/1663977705413.png)]

Since static variables belong to the class, they can be called only by the class name:类名.静态变量

Instance variables belong to objects and need to be called through objects:对象.实例变量

  • The following is a code demonstration (note how static variables and instance variables are called)

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-gEnlcdMZ-1690168860644)(assets/1663978511018.png)]

In order to let everyone understand the execution process of these two member variables more clearly, I will give you a few words here, let's take a look at the memory principle of the above code.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-VIgn4zAM-1690168860657)(assets/1663978808670.png)]

  • Finally to sum up
- 1.类变量:属于类,在内存中只有一份,用类名调用
- 2.实例变量:属于对象,每一个对象都有一份,用对象调用

1.2 Application scenarios of static modified member variables

After learning the basic use of static modified member variables, let's learn about the application of static modified member variables in actual work.

In actual development, if only one piece of data is needed and is expected to be shared (accessed, modified), the data can be defined as a class variable to remember.

Let's look at a case **

Requirements: After the system starts, it is required that the class can remember how many user objects it has created. **

  • Step 1: Define a class first User, and define a static modified variable in the user class to indicate the number of people online;
public class User{
    
    
    public static int number;
    //每次创建对象时,number自增一下
    public User(){
    
    
        User.number++;
    }
}
  • Step 2: Write another test class, create 4 User objects in the test class, print the value of number, and observe whether the value of number is self-incrementing.
public class Test{
    
    
    public static void main(String[] args){
    
    
        //创建4个对象
        new User();
        new User();
        new User();
        new User(); 
        
        //查看系统创建了多少个User对象
        System.out.println("系统创建的User对象个数:"+User.number);
    }
}

Run the above code to see the execution result:系统创建的User对象个数:4

1.3 static modification member method

Dear students, after studying the static modification of member variables, let's learn the method of static modification of members. Member methods are also divided into two categories according to whether they are static: class methods and instance methods

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-gG0BtnkG-1690168860660)(assets/1664004813041.png)]

A statically modified method belongs to a class and is called a class method ; it can be called directly with the class name when calling.

A method without static modification belongs to the object and is called an instance method; when calling, you need to use the object call.

Let's look at a case to demonstrate the basic use of class methods and instance methods

  • First define a Student class, define a class method in the class, and define an instance method
public class Student{
    
    
    double score;
    
    //类方法:
    public static void printHelloWorld{
    
    
        System.out.println("Hello World!");
        System.out.println("Hello World!");
    }
    
    //实例方法(对象的方法)
    public void printPass(){
    
    
        //打印成绩是否合格
        System.out.println(score>=60?"成绩合格":"成绩不合格");
    }
}
  • When defining a test class, pay attention to the difference between class method and object method call
public class Test2{
    
    
    public static void main(String[] args){
    
    
        //1.调用Student类中的类方法
        Student.printHelloWorld();
        
        //2.调用Student类中的实例方法
        Student s = new Student();        
        s.printPass();
        
        //使用对象也能调用类方法【不推荐,IDEA连提示都不给你,你就别这么用了】
        s.printHelloWorld();
    }
}

After figuring out how to call class methods and instance methods, let's talk about the memory principle of static modified member methods with students.

1.类方法:static修饰的方法,可以被类名调用,是因为它是随着类的加载而加载的;
		 所以类名直接就可以找到static修饰的方法
		 
2.实例方法:非static修饰的方法,需要创建对象后才能调用,是因为实例方法中可能会访问实			例变量,而实例变量需要创建对象后才存在。
		  所以实例方法,必须创建对象后才能调用。

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-sxdIxVgk-1690168860662)(assets/1664005554987.png)]

About the two usages of static modified member variables and static modified member methods, this is the end of the study here.

1.4 Tools

After learning the static modification method, we will talk about an application knowledge about class methods, called tool classes.

If all the methods in a class are static, then all the methods in this class can be called directly by the class name, because it is very convenient to call, just like a tool, so such a class is called a tool class.

  • We write a tool class that generates verification codes
public class MyUtils{
    
    
    public static String createCode(int n){
    
    
        //1.定义一个字符串,用来记录产生的验证码
        String code = "";
        
        //2.验证码是由所有的大写字母、小写字母或者数字字符组成
        //这里先把所有的字符写成一个字符串,一会从字符串中随机找字符
        String data = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKMNOPQRSTUVWXYZ";
        
        //3.循环n次,产生n个索引,再通过索引获取字符
        Random r = new Random();
        for(int i=0; i<n; i++){
    
    
            int index = r.nextInt(data.length());
            char ch = data.charAt(index);
            //4.把获取到的字符,拼接到code验证码字符串上。
            code+=ch;
        }
        
        //最后返回code,code的值就是验证码
        return code;
    }
}
  • Then it can be called at any position MyUtilsto createCOde()方法generate any number of verification codes
//比如这是一个登录界面
public class LoginDemo{
    
    
    public static void main(String[] args){
    
    
        System.out.println(MyUtils.createCode());
    }
}
//比如这是一个注册界面
public class registerDemo{
    
    
    public static void main(String[] args){
    
    
        System.out.println(MyUtils.createCode());
    }
}

The use of tools is like this, have you learned it?

In addition, the methods in the tool class are all static, and it is recommended to use the class name to prevent users from calling with objects. We can privatize the constructor of the tool class.

public class MyUtils{
    
    
    //私有化构造方法:这样别人就不能使用构造方法new对象了
    private MyUtils(){
    
    
        
    }
    
    //类方法
    public static String createCode(int n){
    
    
       ...
    }
}

1.5 Notes on static

Dear students, by now we have learned how to call statically modified variables and methods. However, there are still some precautions that need to be explained to everyone. The purpose is to let everyone know that if you make a mistake when using static to write code, you must know why it is wrong and how to correct it.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-ww3zgev6-1690168860665)(assets/1664007168869.png)]

public class Student {
    
    
    static String schoolName; // 类变量
    double score; // 实例变量

    // 1、类方法中可以直接访问类的成员,不可以直接访问实例成员。
    public static void printHelloWorld(){
    
    
        // 注意:同一个类中,访问类成员,可以省略类名不写。
        schoolName = "DTS";
        printHelloWorld2();

        System.out.println(score); // 报错的
        printPass(); // 报错的

        ystem.out.println(this); // 报错的
    }
    
	// 类方法
    public static void printHelloWorld2(){
    
    

    }
    
    // 实例方法
    public void printPass2(){
    
    

    }
    
    // 实例方法
    // 2、实例方法中既可以直接访问类成员,也可以直接访问实例成员。
    // 3、实例方法中可以出现this关键字,类方法中不可以出现this关键字的
    public void printPass(){
    
    
        schoolName = "sisa2"; //对的
        printHelloWorld2(); //对的

        System.out.println(score); //对的
        printPass2(); //对的

        System.out.println(this); //对的
    }
}

1.6 static application (code block)

Dear students, next we will add another knowledge point called code block; code block is divided into two types according to whether there is static modification: static code block and example code block

Let's learn about static code blocks first:

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-4aCz9fwr-1690168860666)(assets/1664007549583.png)]

public class Student {
    
    
    static int number = 80;
    static String schoolName = "sisa";
    // 静态代码块
    static {
    
    
        System.out.println("静态代码块执行了~~");
        schoolName = "sisa";
    }
}

Static code blocks can be executed without creating objects

public class Test {
    
    
    public static void main(String[] args) {
    
    
        // 目标:认识两种代码块,了解他们的特点和基本作用。
        System.out.println(Student.number);
        System.out.println(Student.number);
        System.out.println(Student.number);

        System.out.println(Student.schoolName); // sisa
    }
}

When the above code is executed, it is found that no object is created, and the static code block has already been executed.

Important note about static code blocks: Static code blocks are executed as the class is loaded, and only once.

Let's learn about the example code block

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-T6XWpzsS-1690168860669)(assets/1664008215853.png)]

The role of the instance code block is the same as that of the constructor, which is used to initialize the value of the object; and the instance code block will be executed every time before the object is created.

public class Student{
    
    
    //实例变量
	int age;
    //实例代码块:实例代码块会执行在每一个构造方法之前
    {
    
    
        System.out.println("实例代码块执行了~~");
        age = 18;
        System.out.println("有人创建了对象:" + this);
    }

    public Student(){
    
    
        System.out.println("无参数构造器执行了~~");
    }

    public Student(String name){
    
    
        System.out.println("有参数构造器执行了~~");
    }
}

Next, test in the test class to observe whether the instance code block is executed first when the object is created.

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Student s1 = new Student();
        Student s2 = new Student("张三");
        System.out.println(s1.age);
        System.out.println(s2.age);
    }
}

Important note for the example code block: the example code block will be executed every time before creating an object

3. Construction methods and overloading

3.1 Construction method

A constructor is a special method that initializes members of an object when the object is created, also known as a constructor. It has the following characteristics.
1. The method name of the constructor is the same as the class name.
2. The constructor has no return value and cannot have void.
3. The main function of the construction method is to initialize the class object.
4. Generally, the construction method cannot be directly called by the programmer explicitly, but is called by new.
5. When creating an object of a class, the system will automatically call the constructor of the class to initialize the new object.
6. It can take parameters, and can also complete other complex operations other than assignment

If the constructor is omitted, the Java compiler will automatically generate a default constructor for the class, and the program will automatically call the default constructor when creating an object. The default constructor has no parameters and does not have any code in its method body, that is, it does nothing. If there is a public modifier in front of the class, the default constructor is also public in front of it. Once the user defines a construction method for a certain class, the system no longer provides a default construction method, which is caused by Java's coverage.

About the constructor has been described in Chapter 4.

3.3 Method overloading

One of the three major characteristics of object-oriented: polymorphism: the coexistence of multiple different methods with the same name in a program. Common overloading and overriding (overriding).

Method overloading is one of the ways to achieve "polymorphism".

Characteristics of method overloading:

1. Method overloading means that the method has different parameters, but uses the same name.
2. The different parameters of the method means that different functions are realized, but the functions are similar.
The so-called different parameters refer to: the number of parameters is different, the type of parameters is different, and the order of parameters is different. The difference in the names of the parameters does not indicate that the method is overloaded.
3. Method overloading has nothing to do with the return value

Example:

int  add(int x, int y);
int  add(int x, int y, int z);
float  add(float f1, float f2);
float add(float f1, int y);
float add(int y, float f1);
float  add(int x, int y);
int add(int u, int v);

Overloading of the constructor method: the method name is different but the parameters are different

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

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

Calling another constructor from a constructor must be called through the keyword this, otherwise a compilation error occurs.
The this keyword must be written in the first line of the constructor.

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

    public Student(){
    
    
        System.out.println("空参构造方法");
    }
    public Student(int age,String name){
    
    
        this.Student();
        System.out.println("非空参构造方法");
    }
}

Notice:

构造方法一般都是public,因为它们在创建对象时,是在类的外部被系统自动调用的。
构造函数若被声明为private,则无法在构造方法所在的类以外的地方被调用,但在该类的内部还是可以被调用。

4. Automatic conversion between basic types and wrapper types

Except for boolean and char types, the basic data types can be converted to each other.
1 Basic data type to packaging type – "boxing

int a =10 ;
Integer i1 = a;//可以自动转,自动装箱
Integer a1 = new Integer(a);//手动装箱
Integer i = Integer.valueOf(a);

2 Packing type to basic data type – "unboxing

2 Packing type to basic data type – "unboxing

Integer a =10 ;
int i1 = a;//可以自动转,自动拆箱
int i2 = a.intValue();//手动拆箱

3 Convert the string to a basic data type, and call the parseXXX method or valueOf method of the wrapper class

3 Convert the string to a basic data type, and call the parseXXX method or valueOf method of the wrapper class

String s = "1234";
int i = Integer.parseInt(s);
double b = Double.parseDouble(s);
boolean boo = Boolean.parseBoolean(s);
int i = Integer.valueOf(s);

4 Convert basic data types to strings

int i =9;
//方法1
String s = i+"";
//方法2
String s = String.valueOf(i);
//方法3
String s = Integer.toString(i);

5. Inheritance

5.1 Inheritance Quick Start

Dear students, we continue to learn object-oriented related content. There is a very important reason why object-oriented programming can be recognized by the majority of developers, because it has three major characteristics, inheritance, encapsulation and polymorphism. We have already learned encapsulation in the basic class, and then we will learn about inheritance.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-rLEhmq2k-1690168860671)(assets/1664009338913.png)]

Next, let's demonstrate the use of inheritance to write code, and pay attention to the characteristics of inheritance.

public class A{
    
    
    //公开的成员
    public int i;
    public void print1(){
    
    
        System.out.println("===print1===");
    }
    
    //私有的成员
    private int j;
    private void print2(){
    
    
        System.out.println("===print2===");
    }
}

Then, write a class B and let class B inherit class A. While inheriting class A, add a method print3 to class B

public class B extends A{
    
    
    public void print3(){
    
    
        //由于i和print1是属于父类A的公有成员,在子类中可以直接被使用
        System.out.println(i); //正确
        print1(); //正确
        
        //由于j和print2是属于父类A的私有成员,在子类中不可以被使用
        System.out.println(j); //错误
        print2();
    }
}

Next, let's demonstrate again, whether to create a class B object, can call the members of the parent class A. Write another test class

public class Test{
    
    
    public static void main(String[] args){
    
    
        B b = new B();
        //父类公有成员,子类对象是可以调用的
        System.out.println(i); //正确
        b.print1();
        
        //父类私有成员,子类对象时不可以调用的
        System.out.println(j); //错误
        b.print2(); //错误
    }
}

At this point, we have learned the basic use of inheritance. In order to let everyone have a deeper understanding of inheritance, let's take a look at the memory principle of inheritance.

Here we only need to pay attention to one point: the subclass object is actually created by the two design drawings of the subclass and the parent class.

Therefore, in the space of subclass objects, there are both members of this class and members of the parent class. But the subclass can only call the public members of the parent class.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-gsVXzste-1690168860675)(assets/1664010915416.png)]

5.2 Benefits of Inheritance

Dear students, after learning the quick introduction to inheritance, let's learn the benefits of inheritance and its application scenarios.

We learn through a case
[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-oE44KV1B-1690168860677)(assets/1664011136599.png)]

Observing the code, we will find that the Teacher class and the Consultant class have the same code; in fact, when there is the same code in these two classes, there is no need to rewrite it.

We can extract the repeated code as the parent class, and then let other classes inherit the parent class, which can improve the reusability of the code. The modified code is as follows:

insert image description here

Next, use inheritance to complete the above case. Only the People class and the Teacher class are demonstrated here, and then you try to complete the Consultant class yourself.

  • First write a parent class People to design the public members of Teacher and Consultant.
public class People{
    
    
    private String name;
    
    public String getName(){
    
    
        return name;
    }
    public void setName(String name){
    
    
        this.name=name;
    }
}
  • Write two more subclasses, Teacher, to inherit the People class, and add its own unique members to the subclasses.
public class Teacher extends People{
    
    
    private String skill; //技能
    
    public String getSkill(){
    
    
        return skill;
    }
    
    public void setSkill(String skill){
    
    
        this.skill=skill;
    }
    
    public void printInfo(){
    
    
        System.out.println(getName()+"具备的技能:"+skill);
    }
}
  • Finally, write a test class, create Teacher and Consultant objects in the test class, and call the method.
public class Test {
    
    
    public static void main(String[] args) {
    
    
        // 目标:搞清楚继承的好处。
        Teacher t = new Teacher();
        t.setName("播仔");
        t.setSkill("Java、Spring");
        System.out.println(t.getName());
        System.out.println(t.getSkill());
        t.printInfo();
    }
}

Execute the code and print the result as follows:

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-WNSBSLen-1690168860679)(assets/1664011737379.png)]

The benefits of inheritance we just need to remember: inheritance can improve the reusability of code

5.3 Permission Modifiers

Dear students, in the code written using inheritance just now, we used two permission modifiers, one is public (public) and the other is private (private). In fact, there are two permission modifiers, one is protected (protected), and the other is default (do not write any modifiers).

Next, let's learn what the four permission modifiers do.

What are permission modifiers?

Permission modifiers are used to limit the range in which members of a class (member variables, member methods, constructors...) can be accessed.

The range that each permission modifier can be accessed is as follows

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-u19Fjtsh-1690168860680)(assets/1664012151488.png)]

Let's use the code to demonstrate which permission modification methods can be accessed in this class.

public class Fu {
    
    
    // 1、私有:只能在本类中访问
    private void privateMethod(){
    
    
        System.out.println("==private==");
    }

    // 2、缺省:本类,同一个包下的类
    void method(){
    
    
        System.out.println("==缺省==");
    }

    // 3、protected: 本类,同一个包下的类,任意包下的子类
    protected void protectedMethod(){
    
    
        System.out.println("==protected==");
    }

    // 4、public: 本类,同一个包下的类,任意包下的子类,任意包下的任意类
    public void publicMethod(){
    
    
        System.out.println("==public==");
    }

    public void test(){
    
    
        //在本类中,所有权限都可以被访问到
        privateMethod(); //正确
        method(); //正确
        protectedMethod(); //正确
        publicMethod(); //正确
    }
}

Next, create a test class Demo under the same package as the Fu class to demonstrate which permission modification methods can be accessed under the same package.

public class Demo {
    
    
    public static void main(String[] args) {
    
    
        Fu f = new Fu();
        // f.privateMethod();	//私有方法无法使用
        f.method();
        f.protectedMethod();
        f.publicMethod();
    }
}

Next, create a subclass of the Fu class under another package to demonstrate which permission modification methods can be accessed in subclasses under different packages.

public class Zi extends Fu {
    
    
    //在不同包下的子类中,只能访问到public、protected修饰的方法
    public void test(){
    
    
        // privateMethod(); // 报错
        // method(); // 报错
        protectedMethod();	//正确
        publicMethod();	//正确
    }
}

Next, create a test class Demo2 under a package different from the Fu class, to demonstrate which permission modification methods can be accessed by irrelevant classes in different packages;

public class Demo2 {
    
    
    public static void main(String[] args) {
    
    
        Fu f = new Fu();
        // f.privateMethod(); // 报错
        // f.method();		  //报错
        // f.protecedMethod();//报错
        f.publicMethod();	//正确

        Zi zi = new Zi();
        // zi.protectedMethod();
    }
}

5.4 Single inheritance, Object

In the code we wrote just now, a subclass inherits a parent class, so some students asked, can a subclass inherit multiple parent classes?

The Java language only supports single inheritance and does not support multiple inheritance, but multi-level inheritance is possible . Just like the relationship between son, father and grandfather in a family: a son can only have one father, not multiple fathers, but fathers also have fathers.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-Y3nOdS0z-1690168860684)(assets/1664016601977.png)]

public class Test {
    
    
    public static void main(String[] args) {
    
    
        // 目标:掌握继承的两个注意事项事项。
        // 1、Java是单继承的:一个类只能继承一个直接父类;
        // 2、Object类是Java中所有类的祖宗。
        A a = new A();
        B b = new B();

        ArrayList list = new ArrayList();
        list.add("java");
        System.out.println(list.toString());
    }
}

class A {
    
    } //extends Object{}
class B extends A{
    
    }
// class C extends B , A{} // 报错
class D extends B{
    
    }

5.5 Method Rewriting

Dear students, after studying inheritance, there is another very important phenomenon on the basis of inheritance that I need to tell you.

It's called method overriding. In order for everyone to master method rewriting, let's first understand what method rewriting is, and then talk about the application scenarios of methods.

What is method overriding

When the subclass feels that the method of the parent class is not easy to use, or cannot meet the needs of the parent class, the subclass can rewrite a method with the same method name and parameter list to override the method of the parent class. This is method rewriting.

Note: After rewriting, method access follows the principle of proximity . Let's look at a code demo

Write a class A as the parent class and define two methods print1 and print2

public class A {
    
    
    public void print1(){
    
    
        System.out.println("111");
    }

    public void print2(int a, int b){
    
    
        System.out.println("111111");
    }
}

Write another class B as a subclass of class A, and rewrite the print1 and print2 methods.

public class B extends A{
    
    
    // 方法重写
    @Override // 安全,可读性好
    public void print1(){
    
    
        System.out.println("666");
    }


    // 方法重写
    @Override
    public void print2(int a, int b){
    
    
        System.out.println("666666");
    }
}

Next, create a class B object in the test class and call the method

public class Test {
    
    
    public static void main(String[] args) {
    
    
        // 目标:认识方法重写,掌握方法重写的常见应用场景。
        B b =  new B();
        b.print1();
        b.print2(2, 3);
    }
}

Executing the code, we found that the actual execution is the print1 and print2 methods in class B

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-dzSOOcch-1690168860686)(assets/1664149862001.png)]

After knowing what method rewriting is, there are still some precautions that need to be shared with you.

- 1.重写的方法上面,可以加一个注解@Override,用于标注这个方法是复写的父类方法
- 2.子类复写父类方法时,访问权限必须大于或者等于父类方法的权限
	public > protected > 缺省
- 3. 重写的方法返回值类型,必须与被重写的方法返回值类型一样,或者范围更小
- 4. 私有方法、静态方法不能被重写,如果重写会报错。

Regarding these precautions, students actually only need to know a little bit. In fact, when we actually write the code, as long as it is written in the same way as the parent class (to sum up, it is only 8 words: the declaration remains unchanged, and the implementation is re-implemented )

Application Scenarios for Method Rewriting

After learning about method rewriting, next, we need everyone to master method rewriting and its actual application scenarios. One of the application scenarios of method rewriting is: the subclass rewrites the toString() method of Object in order to return the content of the object.

For example: There is a Student class, which will inherit the Object class by default.

public class Student extends Object{
    
    
    private String name;
    private int age;

    public Student() {
    
    
    }

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

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }
}

In fact, there is a toString() method in the Object class. Calling Object's toString() method directly through the Student object will get the address value of the object.

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Student s = new Student("播妞", 19);
        // System.out.println(s.toString());
        System.out.println(s);
    }
}

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-ZzvJ05c1-1690168860687)(assets/1664150713665.png)]

However, if you don't want to call the toString() method of the parent class Object at this time, you can rewrite a toSting() method in the Student class to return the attribute value of the object.

package com.itheima.d12_extends_override;

public class Student extends Object{
    
    
    private String name;
    private int age;

    public Student() {
    
    
    }

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

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }

    @Override
    public String toString() {
    
    
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Re-run the test class, the result is as follows

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-eLhLeUUI-1690168860689)(assets/1664150752636.png)]

Well, here we have finished learning what is method rewriting and the application scenarios of method rewriting.

5.6 Features of accessing members in subclasses

Dear students, we have learned about inheritance just now, and we found that inheritance involves at least two classes, and each class may have its own members (member variables, member methods), and it is possible that subclasses and parent classes have the same members, so what are the characteristics of accessing other members in subclasses?

  • Principle: Accessing other members (member variables, member methods) in subclasses is based on the principle of proximity

Define a parent class, the code is as follows

public class F {
    
    
    String name = "父类名字";

    public void print1(){
    
    
        System.out.println("==父类的print1方法执行==");
    }
}

Then define a subclass, the code is as follows. There is a name member variable with the same name, and a print1 member method with the same name;

public class Z extends F {
    
    
    String name = "子类名称";
    public void showName(){
    
    
        String name = "局部名称";
        System.out.println(name); // 局部名称
    }

    @Override
    public void print1(){
    
    
        System.out.println("==子类的print1方法执行了=");
    }

    public void showMethod(){
    
    
        print1(); // 子类的
    }
}

Next, write a test class and observe the running results. We found that they are all called subclass variables and subclass methods.

public class Test {
    
    
    public static void main(String[] args) {
    
    
        // 目标:掌握子类中访问其他成员的特点:就近原则。
        Z z = new Z();
        z.showName();
        z.showMethod();
    }
}
  • If there are variables or methods with the same name in the subclass and the parent class, the subclass is used first; at this time, if you must use the members of the parent class in the subclass, you can add this or super to distinguish.
public class Z extends F {
    
    
    String name = "子类名称";

    public void showName(){
    
    
        String name = "局部名称";
        System.out.println(name); // 局部名称
        System.out.println(this.name); // 子类成员变量
        System.out.println(super.name); // 父类的成员变量
    }

    @Override
    public void print1(){
    
    
        System.out.println("==子类的print1方法执行了=");
    }

    public void showMethod(){
    
    
        print1(); // 子类的
        super.print1(); // 父类的
    }
}

5.7 Features of Accessing Constructors in Subclasses

Dear students, we know that member variables, member methods, and constructors can be written in a class. Under the inheritance relationship, we have already learned the characteristics of subclass access to member variables and member methods; next, we will learn the characteristics of access to constructors in subclasses.

Let's first understand the grammatical characteristics of subclass constructors, and then talk about the application scenarios of subclass constructors

Syntax Rules for Accessing Constructors in Subclasses

  • First of all, all constructors of the subclass will first call the constructor of the parent class, and then execute themselves.

    Execution sequence, follow steps ① ② ③ as shown in the figure below:

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-sxNSIlxa-1690168860691)(assets/1664160225526.png)]

Application Scenarios for Subclass Access to Constructors

  • If you don't want to use the default super()way to call the parent class constructor, you can also manually call super(参数)the parent class parameterized constructor.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-zcioyLVN-1690168860693)(assets/1664163881728.png)]

Access your own constructor in this class

Just now we learned through super()and super(参数)can access the constructor of the parent class. Sometimes we also need to access the constructor of our own class. The syntax is as follows

this(): 调用本类的空参数构造器
this(参数): 调用本类有参数的构造器

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-DO8Jlqqv-1690168860694)(assets/1664170865036.png)]

Finally, we are summarized by the usage of this and super

访问本类成员:
	this.成员变量	//访问本类成员变量
	this.成员方法	//调用本类成员方法
	this()		   //调用本类空参数构造器
    this(参数)	  //调用本类有参数构造器
	
访问父类成员:
	super.成员变量	//访问父类成员变量
	super.成员方法	//调用父类成员方法
	super()		   //调用父类空参数构造器
    super(参数)	  //调用父类有参数构造器
    
注意:thissuper访问构造方法,只能用到构造方法的第一句,否则会报错。

6. Garbage collection in the Java language

Garbage collection (Garbage-collection) is an automatic memory recovery function provided by the Java language, which allows programmers to reduce the burden of many memory management and reduce the chance of programmers making mistakes.
When an object is created, the JVM will allocate a certain amount of memory for the object, call the object's constructor and start tracking the object. When the object stops being used, the JVM will reclaim the memory occupied by the object through the garbage collector.
How does Java know that an object is useless? Any object in the system has a reference counter to count.

The benefits of garbage collection:
1. It frees programmers from complex memory tracking, detection and release;
2. It prevents system memory from being released illegally, thus making the system more stable.
The characteristics of garbage collection:
1. Only when an object is not used by any variable of reference type, its memory may be reclaimed by the garbage collector; 2. The collector cannot be forced to execute immediately through the program; 3. When the garbage collector is about to release the memory
of
the useless object, it first calls the finalze() method of the object.

Guess you like

Origin blog.csdn.net/whirlwind526/article/details/131892468