The This action method and field in Java

Source: Internet
Author: User

public class Parent {public void init () {System.out.println ("1 init Parent"); This.demo ();} public void Demo () {System.out.println ("2 demo parent");}}


public class Son extends the Parent {public void init () {super.init (); System.out.println ("3 init son"); This.demo ();} public void Demo () {System.out.println ("4 demo Son");} public static void Main (string[] args) {//Current run class Sonson son = new son (); Son.init ();  Init (son)}}

The output is:

1 init parent4 demo son3 init son<pre name= "code" class= "Java" >4 demo son


When manipulating a method, this refers to the current running class, which in this case refers to son;



A second example:

public class Parent {public String name= "Tom";p ublic void init () {System.out.println (this.name);}}

public class Son extends the Parent {public String name= "Jack";p ublic void init () {super.init (); System.out.println (this.name);} public static void Main (string[] args) {//Current run class Sonson son = new son (); Son.init ();  Init (son) System.out.println ("# #" + son.name); Parent p = new Son (); SYSTEM.OUT.PRINTLN ("* *" + p.name);}}


The output is:
tomjack## jack** Tom

When manipulating a field, it cannot be overridden as a method, whose is Who.


The This action method and field 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.