0

while developing, my brain suddenly came up with a stupid idea and due to that, also a question about understanding.

I was writing a method to shut down my database connection and driver and I thought about after cleaning up my used objects and stuff, just doing this = null and I was pretty sure, that this won't work. But I tried anyways and IntelliJ of course presented me a nicely formatted error message "Variable expected" when hovering over "this".

So I asked myself how "this" is working (huehue, I like the wordplays). I would be very glad if you could explain it to me. I am basically not a newbie in Java but I didn't thought about "this" (xD) 'til now and just used it.

Is it kind of an alias for the current object? Is it final? Is it just a keyword (I know it IS a keyword) with some special behaviour? I would really appreciate understanding one of the most-used words in my source code.

gtgaxiola
  • 9,241
  • 5
  • 42
  • 64
Niklas S.
  • 1,046
  • 10
  • 22
  • *understanding one of the most-used words in my source code.* share your code – Braj Aug 02 '14 at 18:24
  • 1
    *this won't work* how would we know that what is not working? – Braj Aug 02 '14 at 18:25
  • Because I wrote it before. I said `this = null` isn't working. – Niklas S. Aug 02 '14 at 18:26
  • This `this` keyword denotes a value that is a reference to the current object (http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.8.3) – fgb Aug 02 '14 at 18:31
  • I am confused now. Why is the boolean expression `this == other` working but I can't assign something? I mean am I just having a brain lag or is it confusing? – Niklas S. Aug 02 '14 at 18:33
  • 1
    You can only assign things to variables. Think of it like how methods can be used: `getThis() == other` is allowed, `getThis() = null` isn't. – fgb Aug 02 '14 at 18:35
  • Ah, thanks bro. I guess the missing brackets just brainf***ed me. I think I got it now :) – Niklas S. Aug 02 '14 at 18:36

0 Answers0