2 Replies - 649 Views - Last Post: 02 December 2009 - 10:50 AM Rate Topic: -----

#1 polska03  Icon User is offline

  • D.I.C Regular

Reputation: 5
  • View blog
  • Posts: 302
  • Joined: 28-November 09


Posted 01 December 2009 - 11:02 PM

May someone please explain to me what“this” means in a class.
and how “this” can be used in a class. Any help very much appreciated!
Is This A Good Question/Topic? 0
  • +

Replies To: "this"

#2 ianian112  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 119
  • View blog
  • Posts: 378
  • Joined: 28-November 09

Re: "this"

Posted 01 December 2009 - 11:06 PM

they have a really good example in my opinion
Was This Post Helpful? 1
  • +
  • -

#3 japanir  Icon User is offline

  • jaVanir
  • member icon

Reputation: 1014
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: "this"

Posted 02 December 2009 - 10:50 AM

"this" is a keyword. used to state "this object".
which means, that while using it inside a class, you can refer to the object's variables, methods and constructor.
here is a very simple wxample of how to use this in a class:
public class A {

//global variable:
//here i declare int, can be any object though.
private int x;

//the constructor
publuc A(int x){
this.x = x;

/*notice the constructor for a very intersesting use of this.
the constructor of A gets a parameter int x.
but wait! there is also a global variable int x in the class itself.
how would you differ them?
using the keyword this.varName (varName is the variable name) 
you tell both the compile and yourself, that this variable is "this Object's" variable.
and "x" alone is the parameter.

//methods of A
private void methodOne(){
this.x = 2;

public void methodTwo(){

/*see, i used the this followed a method and a variable.
this is rather for you as a programmer, to diffrentiate between methods of other classes, or variables.


there is another use to "this" keyword in the constructor i didn't mention.
also, as i said this keyword refers to this object.
because of that reason, you CANNOT use this inside a static field.
the reason is that a static field is unique to the class itself! and not to every single object of the cass.

however, i also recommend that you read a good tutorial on "this" :P

This post has been edited by japanir: 02 December 2009 - 10:51 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1