key word 'this'
-
Hi Please excuse me if my question sound trivial as I am a novice: Why do we need the key word 'this'? What does it do?
-
Hi Please excuse me if my question sound trivial as I am a novice: Why do we need the key word 'this'? What does it do?
You don't need it, but it refers to member variables or methods of a class:
class Foo
{
private int bar;void int setBar(int bar)
{
this.bar = bar;
}
}this.bar
is the memeber variable,bar
is the message attribute.
Panic, Chaos, Destruction. My work here is done. or "Drink. Get drunk. Fall over." - P O'H
-
Hi Please excuse me if my question sound trivial as I am a novice: Why do we need the key word 'this'? What does it do?
The keyword 'this' refers to the current class you are in. If you write 'this.' while in a class, you can access all members of that class by IntelliSense. 'this' just means 'the current class'. Sounds logical, yes? public class MyClass { private int age = 18; public MyClass { this.age = 20; } } However, 'this' can be omitted. 'this.age' is the same as 'age' while in the same class. Regards, CSTreval
-
Hi Please excuse me if my question sound trivial as I am a novice: Why do we need the key word 'this'? What does it do?
It's also used to call another class constructor from a constructor (sometimes called 'chained constructor calls'):
class Foo
{
public Foo()
{
this(0);
}
public Foo(int i)
{
}
}David Anton Convert between VB, C#, C++, & Java www.tangiblesoftwaresolutions.com
-
You don't need it, but it refers to member variables or methods of a class:
class Foo
{
private int bar;void int setBar(int bar)
{
this.bar = bar;
}
}this.bar
is the memeber variable,bar
is the message attribute.
Panic, Chaos, Destruction. My work here is done. or "Drink. Get drunk. Fall over." - P O'H
Nagy Vilmos wrote:
You don't need it
in fact, you may need
this
, e.g. to pass "yourself" to another object or class method, say when you want to subscribe to an event or a service. FWIW: I do like VB.NET'sMe
keyword, it seems more appropriate thanthis
. :)Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.
modified on Saturday, October 2, 2010 9:05 PM
-
Hi Please excuse me if my question sound trivial as I am a novice: Why do we need the key word 'this'? What does it do?
It's also used to reference an inner class's outer class - but I wouldn't worry about that yet if you're a novice :-D
-
Hi Please excuse me if my question sound trivial as I am a novice: Why do we need the key word 'this'? What does it do?
It (this) always refers to the current instances of classes. This function is used in access members of Constructors,instance methods and instance accessors Qualify Member hidden by similar names and to pass objects as a parameter to other methods this keyword is commonly used. To get more details click on the given link Java Tutorial: this Keyword[^]