Among Java, this use summary. . .

xiaoxiao2021-03-06  115

Note: Refer to JIT (Java in Thinking), the example is there. 1. In a class, this can represent the current instance of this class; for example: public class leaf {private 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 ();}} // /: ~ 2, if multiple constructors are written for a class, then they often need to call another constructor in a constructor to avoid write repeated code. You can use this at this time, for example: //: Flower.java // CALLING CONSTRUCTORS WITH "this"

Public class flower = 0; private string s = new string ("null"); flower (int point) {petalcount = Petals; System.out.Println ("constructor w / int arg only, petalcount =" Petalcount);} Flower (STRING SS) {System.Out.println ("Constructor W / String Arg Only, S =" SS); S = SS;} Flower (String S, INT PETALS) {THIS (Petals); //! This (s); // can't call two! This.s = s; // another use of "this" system.out.println ("string & int args");} flower () {this ("Hi", 47); System.out.Println ("default constructor (no args)");} void print () {//! this (11); // not inside non-constructor! system.out. Println ("Petalcount =" Petalcount "S =" S);} public static void main (string [] args) {Flower X = new flower (); x.print ();}} ///: ~

It is to be noted that using this a class A in the internal class B is not a current instance of A.B, but a current instance of A;

转载请注明原文地址:https://www.9cbs.com/read-102577.html

New Post(0)