Usage of super and this in Java

Source: Internet
Author: User

The code is relatively simple to say, look directly:

1234567891011121314151617181920212223242526272829303132333435363738 classPerson {    publicstaticvoidprt(String s) {        System.out.println(s);    }    Person() {        prt("A Person.");    }    Person(String name) {        prt("A person name is:"+ name);    }}publicclassChinese extendsPerson {    Chinese() {        super(); // 调用父类构造函数(1)        prt("A chinese.");// (4)    }    Chinese(String name) {        super(name);// 调用父类具有相同形参的构造函数(2)        prt("his name is:"+ name);    }    Chinese(String name, intage) {        this(name);// 调用当前具有相同形参的构造函数(3)        prt("his age is:"+ age);    }    publicstaticvoidmain(String[] args) {        Chinese cn = newChinese();        cn = newChinese("kevin");        cn = newChinese("kevin"22);    }}

The key is to look at (1), (2), (3), (4), this refers to the current object, so this (name) invokes the constructor that currently has the same formal parameter.

Super refers to the parent class object, so super (name) calls the constructor of the parent class with the same parameters.

The simpler this. Variable, refers to the variable of the current object. Super. Variable, which is the variable of the parent class

There's a little trick, the parent class name. This is the variable name/method name, at which point this refers to the parent class object.

Usage of super and this in Java

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.