this

Discussion in 'Java' started by mojde, Apr 28, 2012.

  1. mojde

    mojde Guest

    hi all ,
    I can't understand the usages of "this" , could you plz help me ?

    thank you . . .
    mojde, Apr 28, 2012
    #1
    1. Advertising

  2. On 12-04-28 09:33 AM, mojde wrote:
    > hi all ,
    > I can't understand the usages of "this" , could you plz help me ?
    >
    > thank you . . .


    One way of understanding "this" is as part of a larger picture, which is
    understanding what everything is doing at runtime, i.e. when your code
    is executing.

    Once you've fired up a Java application, and execution of code starts
    with a proper main() method in a designated main class [1], objects with
    various lifetimes start to be created. Code in _instance_ methods (as
    opposed to static/class methods) runs in the context of a single object.

    It's this single object that you can refer to as "this". Understand also
    that often, by well-defined rules, you can omit the explicit "this".

    A "this" reference (implicit or explicit) is how you affect the state of
    the object that your instance methods are executing in. See above: when
    an instance method executes it is in the context of one object. Getters
    and setters, for example, wouldn't be very useful unless they could
    access the state of the particular object. Getters and setters are
    simple instance methods themselves.

    Without the "this" reference you effectively lose encapsulation. You'd
    have to make your member fields public, and there really wouldn't be
    instance methods anymore as you'd have to pass object references around
    and that would be useless.

    As an example, consider a rudimentary class Vehicle as

    public class Vehicle {
    private Double speed;

    public Double getSpeed() { return speed; }
    public void setSpeed(Double speed) { this.speed = speed; }
    }

    Those 2 accessor methods are instance methods - whenever that code
    executes they have a context of a single, instantiated Vehicle object.
    So for example,

    Vehicle vehicle1 = new Vehicle();
    vehicle1.setSpeed(15.5);

    When you call setSpeed() on "vehicle1", the 'this' reference in the
    method body is how the code can access the member field "speed", by
    'this.speed', and actually set the value.

    The getter _implicitly_ uses 'this'.

    If you didn't have 'this', things would degrade to

    public class Vehicle {
    public Double speed;
    }

    and

    Vehicle vehicle1 = new Vehicle();
    vehicle1.speed = 15.5;

    There is another usage of 'this' for invoking another constructor from a
    constructor of the same class, but I won't cover that right now.
    Although in a conceptual sense it's yet another mechanism for accessing
    something belonging to the current object.

    AHS

    1. A codebase can have any number of "main" classes. As many of those
    that the codebase has, is how many individual Java applications the
    codebase supports.
    --
    A fly was very close to being called a "land," cause that's what they do
    half the time.
    -- Mitch Hedberg
    Arved Sandstrom, Apr 28, 2012
    #2
    1. Advertising

  3. In article
    <>,
    mojde <> wrote:

    > I can't understand the usages of "this", could you please help me?


    See "Using the this Keyword"

    <http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html>

    --
    John B. Matthews
    trashgod at gmail dot com
    <http://sites.google.com/site/drjohnbmatthews>
    John B. Matthews, Apr 28, 2012
    #3
  4. mojde

    Roedy Green Guest

    On Sat, 28 Apr 2012 05:33:59 -0700 (PDT), mojde <>
    wrote, quoted or indirectly quoted someone who said :

    >I can't understand the usages of "this" , could you plz help me ?


    see http://mindprod.com/jgloss/this.html
    --
    Roedy Green Canadian Mind Products
    http://mindprod.com
    Programmers love to create simplified replacements for HTML.
    They forget that the simplest language is the one you
    already know. They also forget that their simple little
    markup language will bit by bit become even more convoluted
    and complicated than HTML because of the unplanned way it grows.
    ..
    Roedy Green, Apr 28, 2012
    #4
  5. mojde

    Stefan Ram Guest

    mojde <> writes:
    >I can't understand the usages of "this" , could you plz help me ?


    A non-static method »m« may act as a non-static method of an
    object »o«. »this« designates this object »o« within the
    declaration of the method »m«.

    In other words: When a method named »m« was being activated by
    a call »o.m(...)«, wherin »o« is an expression of reference
    type which has the non-null reference »r« as its value, then,
    within the declaration of the method »m«, »this« designates
    this reference »r« during the evaluation of any such call.
    Stefan Ram, Apr 28, 2012
    #5
  6. On 4/28/2012 9:33 PM, mojde wrote:
    > hi all ,
    > I can't understand the usages of "this" , could you plz help me ?
    >
    > thank you . . .


    if you write a class like this:

    class Apple { String color = "";
    setColor(String s) { this.color = s }
    }

    then say you have two apple objects:

    Apple a1 = new Apple();
    Apple a2 = new Apple();

    then when you encounter a statement that says:

    a1.setColor("red");

    the code for a1.setColor encounters "this.color" which refers to that
    object's own color variable.

    Why?

    Because some people do this:

    class Apple { String color = "";
    setColor(String color) { this.color = color }
    }

    Notice now that "this.color" refers to the object's color variable, and
    "color" refers to String color in the scope of the local method.

    There are other reasons. You may want a class to store a handle of
    itself somewhere else. For example, the following method:

    public Apple getInstance() { return this }

    The above method returns the particular instance of Apple. In this case,

    Apple a1 = new Apple;

    Now, the following two statements produce identical results:

    Apple a2 = a1;
    and
    Apple a2 = a1.getInstance();

    You can also use this to call alternate constructors.
    For example;

    Apple () { this("red") }
    Apple (String s) ( setColor(s) }

    One of the more interesting usages of "this" remains passing a reference
    to an object versus defining scope. It can be used to create a way to
    pass a function as an argument. For example, if we have a well-known
    function name encapsulated as a class (think "Thread", "Runnable", or
    "Callable"):

    class Callable { callme(Object o) { /* code here */ } }

    class Println extends Callable { callme(Object o) { println(o); } }
    class Print extends Callable { callme(Object o) { print(o); } }

    Now you can instantiate an instance of CallableFunction, and pass it as
    an argument.
    Println p1 = new Println();
    Print p2 = new Print();

    String = "whatever"
    Callable func = new Print();

    processcommand (func, whatever);

    The code for process command would be as follows, of course:

    processcommand(Callable c, Object o)
    { c.callme(o); }

    This has applications all over the place from parsing XML to storing
    game tree data for a chess file editor, for example, which would allow
    you to traverse back and forth in a tree simply by following the
    commands contained in the command-nodes which comprise the tree. The
    main use here is in processing large numbers of commands. if you have a
    switch statement, for example, containing fifty cases, you might begin
    to wonder if this method finds a result faster, since it directly looks
    up a reference to the code you need to execute (plus one or two extra
    method calls).

    So for example if you're writing a fighting video game you can't be slow
    and have 100 if's or a switch for determining which move to animate
    next; you need to get the move immediately and process it.

    Also it helps you contain the code in one place; if you use a switch,
    there's no guarantee you won't need another separate switch statement
    somewhere else if you need new functionality. Using this method I've
    described you can just write a default behavior into a base class.

    Like lets say your writing a database which searches through a million
    chess games. Say for AI. And you need to traverse a lot of game trees
    and rotate positions and stuff like that. You pretty much have to use
    the this keyword. So it does have it's uses, but for run of the mill
    everyday programming it's safer to just use a simple 5 or 10 case
    switch. Or not. Or whatever.
    Tsukino Usagi, Apr 29, 2012
    #6
  7. mojde

    Lew Guest

    Tsukino Usagi wrote:
    ....
    > One of the more interesting usages of "this" remains passing a reference to an
    > object versus defining scope. It can be used to create a way to pass a
    > function as an argument. For example, if we have a well-known function name


    Excellent example for several reasons.

    > encapsulated as a class (think "Thread", "Runnable", or "Callable"):
    >
    > class Callable { callme(Object o) { /* code here */ } }


    Quibble: This should be an interface, not a class, and we should declare
    pedagogical examples 'public', and most certainly the method should be:

    /* not to be confused with
    <http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Callable.html>
    */
    public interface Callable<T>
    {
    void callMe(T client);
    }

    > class Println extends Callable { callme(Object o) { println(o); } }


    public class Println implements Callable<Object>
    {
    @Override
    public void callMe(Object client)
    {
    System.out.println(client);
    }
    }

    The pattern of single abstract method (SAM) interfaces is so prevalent and
    useful that Java will introduce a sort-of functional syntax for it in Java 8.

    --
    Lew
    Honi soit qui mal y pense.
    http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg
    Lew, Apr 29, 2012
    #7
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.

Share This Page