Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android

Shane McC
Shane McC
3,005 Points

Java keyword "This" confused

Hi Everyone

I have a question regarding the "this" keyword in Java. When I call this.whatever in the println statement it's printing "This is from the String whatever Hi Man!!" how come it's printing "Hi Man!!" and not "Hi Dude!!"?

"Hi Dude!!" is within the scope of the method sayIt so shouldn't it print out "Hi Dude!!" instead of "Hi Dude!!"?

Thanks

public class MorePractice{

    public static void main(String[] args){
        Test mp = new Test ();
        mp.whatever = "Hi Man!!";
        mp.sayIt();
    }
}

class Test{

    String whatever = "Hi Dude!";

    public void sayIt(){
        System.out.println("This is from the String whatever " + this.whatever);
    }

}

1 Answer

JT Keller
JT Keller
12,731 Points

Don't forget that the main method has scope as well. In addition to the scoping, the default constructor for the Test object that you've instantiated is being called, which sets your fields to (null, 0, etc... depending on the type). Think about those 2 things and retrace your steps through the code. Also adding print statements can be a good way step through your code as it is executing.

http://www.cs.berkeley.edu/~jrs/4/lec/08