What is the purpose of this operator?
What is this operator?
Give me codes with "this" operator.
When to use it?
HELP ME WITH THIS!
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
What is the purpose of this operator?
What is this operator?
Give me codes with "this" operator.
When to use it?
HELP ME WITH THIS!
The this operator is used to refer to the current context - in other words, the object that you are dealing with right now.
Consider a class called Person that expects some parameters like name, age during instantiation, you can then set those properties by calling this.property = property_passed_in to the constructor.
When the Person object is created, its properties name and age will be set. I hope this helps.public Class Person{ private String name; private int age; public Person(String name, int age){ this.name = name; this.age = age; } }
crys (August 29th, 2013)
Think of any dot-separated operators you add before a var name in the context of an ascending pyramid.
If you have a method in a class, and you refer to x, that's x in the method.
If you refer to this.x, that's the x in the class.
If you refer to anotherClass.x, that's x in another class.
No operators = closest x. Then comes this, then comes specifying where this "x" you speak of is.
-s45
As mentioned above the this operator is used to refer to the current object. Another use is when you need to call a method in another class that has a parameter of the current class.
class Bar { public void doStuff(Foo f) { } } class Foo { private Bar b = new Bar(); public void someMethod() { b.doStuff(this); } }
Improving the world one idiot at a time!