Super and this in Java

Source: Internet
Author: User

Super keyword

In a subclass that represents a reference to a parent class object, you can call the properties of a method in the parent class in a subclass.

Super Statement---Subclass after inheriting the parent class, the child class will have a super statement in its construction method.

If the super statement is not manually specified, the parent class is called without a parameter by using super ().

If the parent class only provides a parameter-only construct, the subclass must manually provide the corresponding form of the super statement

NOTE: The super statement must be in the first row of the subclass construction method

The use of 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
classCountry {String name; voidvalue () {Name= "China"; }}  classCityextendsCountry {String name; voidvalue () {Name= "Shanghai"; Super. value ();//calling a method of the parent classSystem.out.println (name); System.out.println (Super. Name); }       Public Static voidMain (string[] args) {City C=NewCity ();       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.

Instance:

Animal.class

class Animal {// parent class public    int -age =one        ;  Public Animal () {        System.out.println ("parent class constructor!) ");    }          Public void eat () {        System.out.println ("animals need to eat ~ ~");}    }

Dog.class

 Public classDogextendsanimal{//sub-class    intAge = 20;  PublicDog () {System.out.println ("Sub-class construction Method! "); }         Public voideat () {System.out.println ("The dog needs to eat something ~ ~"); }         Public voidmethod () {Super. Eat ();//call the Eat method of the parent classSystem.out.println (Super. age);//get the Age property of the parent classSystem.out.println (age);//get the Age property of a subclass            }}
Intail. Class
 Public class Intail {    publicstaticvoid  main (string[] args) {        new // instantiation of        // constructor method for calling subclasses         D.method ();            }}

Operation Result:

Parent class Constructor! Sub-class construction Method! Dogs need Food ~ ~ animals need to eat ~~1120

We found that the constructor method of the parent class was instantiated when the constructor of the subclass was instantiated, and for what?

That is because in the subclass of the constructor of the implicit invocation of the parent class of the non-parametric construction method;

But if there is only one constructor in the sub-subclass, you need to write super (parameters, arguments) to invoke the constructor of the parent class.

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)
classPerson { Public Static voidprt (String s) {System.out.println (s); } person () {PRT ("Parent class • No parameter Construction method:" + "A person."); }//construction Method (1)Person (String name) {PRT ("Parent Class • Construction method with one parameter:" + "a person's name is" +name); }//construction Method (2)}      Public classChineseextendsPerson {Chinese () {Super();//calling the Parent class construction method (1)PRT ("Subclass • Call the parent class without parameter construction 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 to construct method with one parameter:" + "his name is" +name); } Chinese (String name,intAge ) {         This(name);//call a construction method with the same parameter (3)PRT ("Subclass: Constructor method for calling subclasses with the same formal parameters: His-age is" +Age ); }          Public Static voidMain (string[] args) {Chinese CN=NewChinese (); CN=NewChinese ("CJJ"); CN=NewChinese ("Cjj", 22); } }

Operation Result:

Parent class • Parameterless construction method: a person. Subclass • Call the parent class without parameter construction method: a Chinese coder.
Parent class • Construction method with one parameter: A person'sname is CJJ Subclass • Call the parent class with a constructor for the parameter: his name is CJJ
Parent class • Construction method with one parameter: A person's name iscjj22
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.

Super and this 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.