-2

Alright, so I am new to Java and have a quick question for anyone who would be nice enough to answer it.

What object is this doSomething method called on? Is it the same as calling this.doSomething()?

public class Something{

    public void doSomething(){
         System.out.println("Something is done");
    }

    public Something(){
    //what object is this being called on?
       doSomething();
    }

    public static void main(String[] args){
        Something foo = new Something();
    }
}

Any help is appreciated!

arsenalfc
  • 1
  • 1
  • 2
    yes. check more details on http://stackoverflow.com/questions/3728062/what-is-the-meaning-of-this-in-java – sdfacre Mar 30 '16 at 00:32

3 Answers3

0

what object is this being called on?

The reference which is going to be assigned to foo, in the scope of the constructor it is the this reference. And yes, doSomething(); (in this context) is equivalent to this.doSomething();

We can see this is the case by adding a UUID to Something (and displaying it in doSomething),

public Something() {
    uuid = UUID.randomUUID().toString();
    doSomething();
}
private final String uuid;
public void doSomething() {
    System.out.println(uuid);
}

and then calling doSomething() again in main like

public static void main(String[] args) {
    Something foo = new Something();
    foo.doSomething();
}

And you'll get the same UUID twice.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

Yes, doSomething is defined within the Something class. Therefore, that is the same as this.doSomething().

To call the doSomething() (declared within "Something" class) from outside the class, you would need to call it like so:

public static void main(String[] args){
    Something foo = new Something();
    foo.doSomething();
}
st_443
  • 51
  • 1
  • 6
0

Yes. Calling this.doSomething is same as calling doSomething(). Not sure what GUI are using. For example if you use Eclipse and have the below code and you click on doSomething it will take you to the void doSomething method. using this is just a reference to the current instance. More details can be found regarding this http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

public class Something{

    public void doSomething(){
         System.out.println("Something is done");
    }

    public Something(){
    //what object is this being called on?
       this.doSomething();
    }

    public static void main(String[] args){
        Something foo = new Something();
    }
}
LearningPhase
  • 1,277
  • 1
  • 11
  • 20