Table of Contents
Code Demonstration:
1. Overview
3.使用
3.1 调用属性和方法
3.2 调用构造器
三、this和super的区别
四、子类对象实例化的全过程
Home Java javaTutorial Detailed analysis of Java's this and super keywords

Detailed analysis of Java's this and super keywords

Apr 30, 2022 am 09:00 AM
java

This article brings you relevant knowledge about java, which mainly introduces the related issues about this and super in keywords, as well as some of their differences. Let’s take a look at them together. I hope everyone has to help.

Detailed analysis of Java's this and super keywords

## Recommended study: "

java video tutorial"

## 1. Use of the "this" keyword

1. Overview

    What is this?
In Java, the
this

keyword is difficult to understand. Its function is very close to its meaning, which means "current".

2. Function

this

keyword can be used to modify and call: properties, methods, and constructors. this
Keywords can only be used inside methods. It is used inside a method, that is, a reference to the object to which this method belongs; It is used inside a constructor, indicating the object being initialized by the constructor.

3. Use

    When should you use this keyword?
When you need to use the object that calls the method within a method, use
this

. Specific: We can use this to distinguish properties and local variables. For example: this.name = name;

3.1 Modify attributes and methods

this

is understood as: the current object or The object currently being created In the method of the class, we can use this.property
or this.method to call the current object properties or methods. However, usually, we choose to omit this.. In special cases, if the formal parameter of the method has the same name as the attribute of the class, we must explicitly use this.variable to indicate that the variable is an attribute, not a formal parameter. When using this
to access properties and methods, if they are not found in this class, they will be searched from the parent class.

Code demonstration:

class Person{ // 定义Person类
    private String name ;
    private int age ;
    public Person(String name,int age){
      this.name = name ; 
      this.age = age ; }
    public void getInfo(){
      System.out.println("姓名:" + name) ;
      this.speak();
    }
    public void speak(){
      System.out.println(“年龄:” + this.age);
    } }
Copy after login
3.2 Calling the constructor

In the constructor of the class, we can use
this.property

or this.method, call the properties or methods of the object currently being created. However, usually, we choose to omit this.. In special cases, if the formal parameters of the constructor have the same name as the attributes of the class, we must explicitly use this.variable to indicate that the variable is an attribute, not a formal parameter.

In the constructor of the class, we can explicitly use
this (formal parameter list)

to call other constructors specified in this class.

The constructor cannot call its own constructor through the
this (formal parameter list)

method.

If there are n constructors in a class, then
there are at most n - 1

this (formal parameter list)# is used in the constructor

## Regulations:
this (formal parameter list)
must be declared in the first line

of the current constructor.

Inside the constructor,
can only declare at most one

this (formal parameter list), which is used to call other constructors.

Except for the constructor, the compiler prohibits calling the constructor in any other method.

Code Demonstration:

class Person{ // 定义Person类
   private String name ;
   private int age ;
   public Person(){ // 无参构造器
     System.out.println("新对象实例化") ;
   }
   public Person(String name){
     this(); // 调用本类中的无参构造器
     this.name = name ;
   }
   public Person(String name,int age){
     this(name) ; // 调用有一个参数的构造器
     this.age = age;
   }
   public String getInfo(){
     return "姓名:" + name + ",年龄:" + age ;
   } }
Copy after login
3.3 Return the current object

Code Demonstration:

public class Leaf {
    int i = 0;
    Leaf increment(){
        i++;
        return this;
    }
    void print(){
        System.out.println("i = "+i);
    }
    public static void main(String args[]){
        Leaf x = new Leaf();
        x.increment().increment().increment().print();//i = 3
    }}
Copy after login
2. Use of "super" keyword

1. Overview

(1)

super
is understood as: parent class

(2) Use super in a Java class to call the specified operation in the parent class:
super

can be used to access the ## defined in the parent class #Attributes
. super can be used to call

member methods

defined in the parent class. super can be used to call the parent class's constructor
in the subclass constructor. Especially when a member with the same name appears in a child or parent class, you can use super to indicate that the member in the parent class is being called. The tracing of super
is not limited to the direct parent class. The usage of super is similar to this
. this represents the reference of this class object, and super represents the memory space of the parent class. logo. 2. Use

to explicitly call the structure of the parent class in the subclass.

3.使用

3.1 调用属性和方法

我们可以在子类的方法或构造器中。通过使用"super.属性“或”super.方法“的方式,显式的调用父类中声明的属性或方法。但是,通常情况下,我们习惯省略”super."。

当子类和父类中定义了同名的属性时,我们要想在子类中调用父类中声明的属性,则必须显式的使用"super.属性"的方式,表明调用的是父类中声明的属性。

当子类重写了父类中的方法以后,我们想在子类的方法中调用父类中被重写的方法时,则必须显式的使用"super.方法"的方式,表明调用的是父类中被重写的方法。

3.2 调用构造器

(1)子类中所有的构造器默认都会访问父类中空参数的构造器

(2)当父类中没有空参数的构造器时,子类的构造器必须通过this(参数列表)或者super(参数列表)语句指定调用本类或者父类中相应的构造器,否则编译出错。同时,只能”二选一”,不能同时出现,且必须放在构造器的首行。

(3)在类的多个构造器中,至少有一个类的构造器中使用了"super(形参列表)",调用父类中的构造器。

代码演示:

public class Person {
    private String name;
    private int age;
    private Date birthDate;
    public Person(String name, int age, Date d) {
       this.name = name;
       this.age = age;
       this.birthDate = d; }
    public Person(String name, int age) {
       this(name, age, null);
    }
    public Person(String name, Date d) {
       this(name, 30, d);
    }
    public Person(String name) {
       this(name, 30);
    } }public class Student extends Person {
    private String school;
    public Student(String name, int age, String s) {
      super(name, age);
      school = s; 
    }
    public Student(String name, String s) {
      super(name);
      school = s; 
    }// 编译出错: no super(),系统将调用父类无参数的构造器。
    public Student(String s) { 
      school = s; 
    } }
Copy after login

三、this和super的区别

No. 区别点 this super
1 访问属性 访问本类中的属性,如果本类没有此属性则从父类中继续查找 直接访问父类中的属性
2 调用方法 访问本类中的方法,如果本类没有此方法则从父类中继续查找 直接访问父类中的方法
3 调用构造器 调用本类构造器,必须放在构造器的首行 调用父类构造器,必须放在子类构造器的首行

四、子类对象实例化的全过程

(1)从结果上来看:(继承性)
 子类继承父类以后,就获取了父类中声明的属性或方法。
 创建子类的对象,在堆空间中,就会加载所有父类中声明的属性。

(2)从过程上来看:
当我们通过子类的构造器创建子类对象时,我们一定会直接或间接的调用其父类的构造器,进而调用父类的父类的构造器,…直到调用了java.lang.Object类中空参的构造器为止。正因为加载过所有的父类的结构,所以才可以看到内存中有父类中的结构,子类对象才可以考虑进行调用。

(3)明确:虽然创建子类对象时,调用了父类的构造器,但是自始至终就创建过一个对象,即为new的子类对象。

推荐学习:《java视频教程

The above is the detailed content of Detailed analysis of Java's this and super keywords. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles