Usage of this and super in Java classes

Source: Internet
Author: User

I. Basic Knowledge

1. Super (parameter): calls a constructor in the base class (the first statement in the constructor). Therefore, the inheritance part of the object is initialized first. if the first clause is not called by super, the super class null Constructor (Super () is automatically called as the first statement.

2. This (parameter): Calls another constructor in this class (it should be the first statement in the constructor)

3. Super: it refers to the members of the direct parent class of the current object (used to access member data or functions of the hidden parent class in the direct parent class, when the base class and the derived class have the same member definition)

For example, super. variable name
Super. Member letter data name (real parameter)

4. This: it indicates the name of the current object (inProgramThis should be used to specify the current object when it is prone to ambiguity. If the form of a function participates in a class with the same name of member data, this is required to specify the member variable name)

II. Application Instances

Class Point
{Private int X, Y;
Public point (int x, int y)
{
This. x = x; // This indicates the current object name.
This. Y = y;
}
Public void draw ()
{
}
Public point ()
{
This (0, 0); // This (parameter) calls another constructor in this class.
}
}
Class circle extends point
{
Private int radius;
Public circle (INT x0, int y0, int R)
{
Super (x0, y0); // super (parameter) calls a constructor in the base class
Radius = R;
}
Public void draw ()
{
Super. Draw (); // super it references members in the direct parent class of the current object
Drawcircle ();
}}

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.