Summary of usage of this and super in Java

Source: Internet
Author: User

These days to see the class in the inheritance will use this and super, here do a little summary, with you to communicate, there are errors please correct me ~

First, this

This is an object of its own, representing the object itself, which can be understood as: A pointer to the object itself.

The usage of this can be broadly divided into 3 types in Java:

1. Normal Direct references

This does not have to be said, this is equivalent to pointing to the current object itself.

2. The name of the member who participates in the membership is distinguished by this:

Package Com.demo;public class Person {        private int: age = ten;        Public person () {        System.out.println ("Initialization Age:" +age);    }        public int Getage (int.) {        this.age = age;        return this.age;}    }
Package Com.demo;public class Test1 {public        static void Main (string[] args) {person        Harry = new Person ();        System.out.println ("Harry's Age is" +harry.getage);}    }

Operation Result:

Age of initialization: 10Harry ' s is 12

3. Reference constructors

Let's talk about this with super, see below.

Second, super

Super can be understood as a pointer to a super (parent) class object, which refers to a parent class closest to itself.

There are three ways to use super:

1. Normal Direct references

Like this, super is the parent class that points to the current object, so you can refer to the members of the parent class with Super.xxx.

2. The member variable or method in the subclass has the same name as a member variable or method in the parent class

Package Com.demo;public class Country {    String name;    void value () {       name = "China";    }}
Package Com.demo;public class City extends country{    String name;    void value () {        name = "Shanghai";        Super.value (); Call the parent class method        System.out.println (name);        System.out.println (Super.name);    }    public static void Main (string[] args) {city        c = new City ();        C.value ();    }}

Operation Result:

Shanghaichina

As you can see, both the methods of the parent class are called and the variables of the parent class are called. If you do not call the parent class method value () and only call the parent class variable name, the parent class name value is the default value NULL.

3. Reference constructors

Super (parameter): Invokes one of the constructors in the parent class (which should be the first statement in the constructor). This (parameter): Call the constructor of another form in this class (should be the first statement in the constructor).
Package Com.demo.test;public class Person {public    static void prt (String s) {        System.out.println (s);    }    Person () {        PRT ("parent class • Parameterless constructor method:" + "A person.");    Construction method (1) Person    (String name) {        PRT ("parent class • Constructor with one parameter:" + "a person's name is" + name);    } Construction method (2)}
Package Com.demo.test;public class Chinese extends person {    Chinese () {        super ();//Call Parent class construction Method (1)        prt ("Subclass • Call the parent class "No parameter constructor method": "+" A Chinese coder. ")    ;    Chinese (String name) {        super (name);//Call the parent class with the same formal parameter construction method (2)        prt ("Subclass • Call Parent class" constructor with one parameter ":" + "his name is" + name); 
   }    Chinese (String name, int age) {This        (name);//Call a construction method with the same formal parameter (3)        prt ("Subclass: Constructor method for calling a subclass with the same formal parameters: His-age is" + age);    }    public static void Main (string[] args) {        Chinese cn = new Chinese ();        cn = new Chinese ("Codersai");        cn = new Chinese ("Codersai");    }}

Operation Result:

Parent class • Parameterless construction method: a person. Subclass • Call the parent class "parameterless constructor method": A Chinese coder. Parent class • Constructor with one parameter: A person's name is Codersai subclass • Call the parent class "constructor with one parameter": his  Name is Codersai parent class • Constructor with one parameter: A person's name is Codersai subclass • Call the parent class "constructor with one parameter": The name is Codersai subclass: The constructor of the calling subclass with the same formal parameters: his Age is 18

As you can see from this example, you can use super and this to call the constructor of the parent class and other forms of construction methods in this class, respectively.

In the example Chinese class, the third constructor method calls the second construction method in this class, and the second constructor calls the parent class, so the constructor of the parent class is called first, the second in this class is called, and the third method of construction is overridden.

The similarities and differences between super and this

    • Super (parameter): Call one of the constructors in the base class (should be the first statement in the constructor)
    • This (parameter): Calls another form of the constructor in this class (should be the first statement in the constructor)
    • Super: It refers to a member in the immediate parent class of the current object (used to access member data or functions in the parent class that is hidden in the immediate parent class, when the base class has the same member definition as in the derived class, such as super. Variable name super. member function by name (argument)
    • This: it represents the current object name (where it is easy to generate two semantics in the program, you should use this to indicate the current object, if the function's shape participates in the class member data has the same name, this should be used to indicate the member variable name)
    • The call to super () must be written on the first line of the subclass construction method, otherwise the compilation does not pass. The first statement of each subclass construction method is implicitly called super (), and if the parent does not have this form of constructor, it will be error-free at compile time.
    • Super () is similar to this (), except that super () calls the constructor of the parent class from the subclass, and this () invokes other methods within the same class.
    • Super () and this () all need to be placed in the first row within the construction method.
    • Although you can call a constructor with this, you cannot call two.
    • This and super can not appear in a constructor at the same time, because this is bound to call other constructors, the other constructors will inevitably have a super statement exists, so in the same constructor has the same statement, it loses the meaning of the statement, the compiler will not pass.
    • This () and super () all refer to objects, so they cannot be used in a static environment. Includes: static variable, static method, static statement block.
    • Essentially, this is a pointer to this object, but super is a Java keyword.

First, this

The Java keyword This can only be used in the method body. When an object is created, the Java Virtual Machine (JVM) assigns a pointer to the object that refers to itself, which is the name of this pointer. Therefore, this can only be used in non-static methods in the class, and the static method and the static code block must never appear in this. And this is only associated with a particular object, not with a class, and different objects of the same class have different this. A comprehensive example using this is given below to illustrate the problem:

Package Com.demo.test;public class Testthis {private int number;    Private String username;    private String password;    private int x = 100;    public testthis (int n) {number = N;//This can also be written as: this.number=n;        The public testthis (int i, string username, string password) {//member variable and parameter have the same name, the member variable is masked, and the member variable is accessed in the way "this. Member variable".        This.username = Username;    This.password = password; }//default constructor with no parameters public testthis () {This (0, "Unknown", "empty");//Call another constructor method through this} public testthis (String na Me) {This (1, name, "null");//Call another construction method through this} public static void Main (String args[]) {Testthis T1 =        New Testthis ();        Testthis t2 = new Testthis ("visitor");        T1.outinfo (t1);    T2.outinfo (T2);        } private void Outinfo (Testthis t) {System.out.println ("-----------");        System.out.println (T.number);        System.out.println (T.username);        System.out.println (T.password); f ();    This can be written as: This.f (); } PRThe ivate void F () {///local variable has the same name as the member variable, the member variable is masked, and the member variable is accessed in the way "this. Member variable".        int x;        x = this.x++;        SYSTEM.OUT.PRINTLN (x);    System.out.println (this.x);    }//Returns a reference to the current instance private Testthis Getself () {return this; }}

The results of the operation are as follows:

-----------0 Unknown empty 100101-----------0 visitors empty 100101

Look at the example above to illustrate the circumstances under which this is required:

First, the use of this call another constructor method, the usage is this (argument list), this is only in the construction method of the class, other places can not be used.

Second, in the case of a function parameter or local variable in a function with the same name as a member variable, the member variable is masked, and the member variable needs to be referenced by the "this. Member variable name" method to access the member variable. Of course, in the absence of the same name, you can directly use the name of the member variable, instead of this, use is not wrong, hehe.

Third, in the function, it is necessary to refer to the current object of the class that the function belongs to, directly with this. In fact, these usage summary is from the "This is a pointer to the object itself" this sentence of a deeper understanding of the word, rote or easy to forget and easy to make mistakes, to understand!

Second, super

The Super keyword is similar to this, making a masked member variable or member method visible, or used to refer to a masked member variable and member method. However, super is used in subclasses in order to access the masked members in the immediate parent class, and note that the immediate parent class is the closest superclass on the class. Here is an example of a comprehensive use of super, there are two classes: A Father class, a subclass of the Father class son, through these two classes fully demonstrates the use of super, the following is the code:
Package Com.demo.test;public class Father {public    String v = "Father";    Public String x = "The public member variable x!!! of the Father class is output";    Public Father () {        System.out.println ("Father constructor method is called!");    Public Father (String v) {        this.v = "Father class with parametric construction Method!";    public void Outinfo () {        System.out.println ("Father Outinfo method called");    }    public static void Main (string[] args) {        //TODO auto-Generate Method stub    }}
Package Com.demo.test;public class Son extends Father {public String v = "Son";        Public Son () {super ();//Call the constructor of the superclass, which can only be placed on the first row.        System.out.println ("Son parameterless constructor method is called!"); Super ();    The wrong one must be placed at the front of the construction method body.        } public Son (String str) {super (str);    System.out.println ("Son with parameter constructor method is called!");    }//Overrides the superclass member Method Outinfo () public void Outinfo () {System.out.println ("son's Outinfo () method is called"); System.out.println (v); Output local variable v System.out.println (THIS.V); Output (subclass) member variable v System.out.println (SUPER.V);        Output Super class member variable v System.out.println ("------2-----"); SYSTEM.OUT.PRINTLN (x); Output Super class member variable V, subclass inherits from System.out.println (super.x);        Output Super class member variable v System.out.println ("------3-----"); Outinfo (); Call the subclass Outinfo () method This.outinfo (); Call the subclass Outinfo () method Super.outinfo (); Call the Outinfo () method of the parent class   public static void Main (string[] args) {new Son (). Test (); }}

Operation Result:

Father constructor method is called! Son parameterless construction method is called!------1-----haha! Sonfather------2-----Output The public member variable x for the Father class!!! The public member variable x for the Father class is output!!! ------3-----Son's Outinfo () method is called by the Outinfo () method of son called Father the Outinfo method is called

Note: This example is intended only to illustrate the use of super, which is generally as private as possible when designing a class.

In the above example, the following summarizes the use of super:

First, in the subclass construction method to invoke the parent class's constructor method, called with "super (parameter list)", the parameter is not necessary. It is also important to note that the "super (parameter list)" statement can only be used in the first row of the subclass in which the method body is constructed.

Second, when a local variable in a subclass method or a member of a subclass has the same name as a parent class member variable, that is, when a subclass local variable overrides the parent class member variable, a "super. Member variable name" is used to refer to the parent class member variable. Of course, if the member variables of the parent class are not overwritten, you can also refer to the parent class member variable with "super. Member variable name", but this is unnecessary.

Thirdly, when the member method of a subclass overrides the member method of the parent class, that is, the subclass and parent class have exactly the same method definition (but the method body can be different), at this point, the method of the parent class is accessed with "super. Method name (parameter list)".

The use of this, super, but only to understand the principles of the principle, will not fall into the trap!

Summary of the usage of this and super in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.