Keywords in Java (this, super...)

Posted by vangelis on Wed, 12 Jan 2022 09:50:27 +0100

catalogue

1, this

2, super

3, static

4, final

5, finalize and fianlly

1, this

  1. First of all, you should know that this is a keyword and translate it into this
  2. This is a reference variable, so it stores an address, but this is a special address, which stores an address pointing to itself.
  3. package com.ThisTest;
    
    public class Student {
        private String name;
        public Student(String name) {
            this.name = name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getName() {
            return name;
        }
        public void work(){
            System.out.println(this.getName()+"at work");
        }
    }
    

    The above is a student class. Observe the following test class

    package com.ThisTest;
    
    public class TestMain {
        public static void main(String[] args) {
            Student s=new Student("Zhang San");
            s.work();//The output result is: Zhang San is working. Because s calls the work method in student, s is this
            Student s2=new Student("Li Si");
            s2.work();//The output result is: Li Si is working, because s2 calls the method in student, s2 is this
        }
    }

    So no matter which object calls a method containing this, this will replace which object

  4. This can only appear in instance methods, not static methods, that is, this cannot appear in methods with static keyword on the modifier list of methods, such as public static void main().

  5. In most cases, this can be omitted, but it cannot be omitted when it is used to distinguish local variables from instance variables. Generally, when using the construction method and set (), whether using idea or eclipse, it is basically generated automatically, so you may not notice here, so you should remember that this cannot be saved in the construction method and set.

2, super

  1. Both this and super are keywords in Java. The usage method is similar, but they are not a reference variable (no variable). There is no address in them, which represents the parent characteristics of the current object.
  2. Super cannot appear in a method with static keyword. In the first line of the construction method, Java will provide a super () by default, or you can manually call the method in the parent class with super (argument). If you manually add a super () in the construction method, you must write it in the first line of the construction method.
  3. package com.SuperTest;
    
    //customer is the parent class
    
    public class Customer {
        private String name;
        private int age;
        public Customer(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
        public void setAge(){
            this.age=age;
        }
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
        public void welcome(){
            System.out.println("Hello!");
        }
    }
    
    package com.SuperTest;
    
    //vip is a subclass
    
    public class Vip extends Customer {
        public Vip(String name) {
            super(name);//One of super usage: Super (argument)
        }
        public void show(){
            System.out.println(this.getName()+"Hello");//The previous this is usually omitted
            System.out.println(super.getName()+"Hello");//Super usage 2: super Attribute name
            super.welcome();//Super usage 3: super Method name
        }
    }
    
    package com.SuperTest;
    
    public class TestMain {
        public static void main(String[] args) {
            Vip v=new Vip("Zhang San");
            v.show();
    
        }
    }
    

    The final output result is hello Zhang San, hello Zhang San, Hello!. customer is the parent class and VIP is the child class. Write a name attribute in the parent class and inherit it in the child class, VIPs. Therefore, after assigning a value to the name in the child class and then using super in the child class, it will be assigned to the name attribute in the parent class.

  4. Summarize the usage of the following super:
  • Super (argument): used in the first line of the construction method to call the parent class construction method
  • super. Property name: access the property in the parent class
  • super. Method name: access the method in the parent class

3, static

Object A and object B have common characteristics. By abstracting these common characteristics, A template and A concept form A class. For example, Chinese Zhang San and Li Si have common characteristics: they both have name, age, gender, nationality They can be formed into A Chinese class. At that time, different objects such as Zhang, San, Li and Si will be created through the new construction method. Each object will occupy A piece of memory space (name, age, nationality, etc.). There is an attribute with the same value (nationality) for all objects. They are all Chinese. If you assign A value to the nationality every time you create an object when calling the construction method, you will waste unnecessary memory space. Therefore, nationality can be promoted to A template. In this case, you need to add A static keyword and assign values at the same time. That is, private static String country = "China", which eliminates the assignment of nationality when creating objects, and reduces the waste of unnecessary memory

4, final

  1. Final is a keyword that represents the final
  2. A class modified by final cannot be inherited
  3. A method modified by final cannot be overridden
  4. Once the value of the attribute modified by final is determined, it cannot be modified
  5. final and static are used together to define constants

public final class A {} / / the class modified by final cannot be inherited

Public class B extensions A {} / / error, because A is modified by final

public class C{ public final void m(){......} } / / a method modified by final cannot be overridden

public class D extends C{ public  void m(){......} } / / error because m is decorated by final

public class Test{

        public static void main(string[]args){

            fianl int a=10; / / once the value of the attribute modified by final is determined, it cannot be modified

             a=21; / / error, because a is modified by final

               public static final String COLRE="red";// Final and static are used together to define constants

        }

}

5, finalize and fianlly

1,finalize

fianllize is a method in the object class. The source code is:

protected void finalize()throws Throwable{

}

There is no code in it. There is only one method body. When will this method be called? When an object in Java becomes garbage, the jvm will automatically enable the garbage collector. The garbage collector automatically calls the fianlize method, which does not need to be called manually by the programmer. Fianlize () is actually a garbage destruction opportunity provided by sun company for Java programmers. If you want to execute a piece of code during garbage destruction, you need to write it in this place, It is equivalent to the last words left by people before saying goodbye to the beautiful world. All classes inherit the object class directly or indirectly, so we only need to rewrite fianlize(). However, the garbage collector will not start easily, but it can be started through system The GC () method improves the efficiency of startup. The efficiency is only improved, not started.

2,finally

The code in the finally clause is executed last and will be executed. Finally, it must be used with try. When it is used with try, it can be used without catch, but not only with catch. Even try {...} catch{. . . } An exception in the code in the statement must also be the statement block in the sink star finally, so the resource is generally released and closed in fianlly.

package com.SuperTest;

public class TestMain {
    public static void main(String[] args) {
        try {
            System.out.println("I took the first step");
            return ;//Step 3 execute the return statement
            
        }finally {
            //If the following code block is not placed in the finally statement, the following sentence will not be executed
            System.out.println("I did the second step");
        }

    }
}

Topics: Java