Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

can somebody please explain the function of "this"

  Asked By: Pamela    Date: Aug 08    Category: Java    Views: 974
  

can somebody please explain the function of "this".With some example.
Thanks

Share: 

 

2 Answers Found

 
Answer #1    Answered By: Stacie Martin     Answered On: Aug 08

class Student
public String name = "John Doe";
public int type = 0;
public int tutor = 2;

public Student(String n, int s, int t)
{
this.name = n;
this.type = s;
this.tutor = t;
}

}

This refers to the current class.

It is more useful when inheriting as you can call an inherited method
using this, which would have been quite hard to do if this did not
exist.

What I have done in the above example  is to set attributes to
parameters.

 
Answer #2    Answered By: Adali Fischer     Answered On: Aug 08

i'd like to say that there is a case you must
use "this" keyword this case if the parameter or a function  the same
as the attributes of the class like this example

class Student
{
private String name;
private int age;
private String email;
public Student()
{
name="";
age=0;
email="";
}
public Student(String name,int age,String email)
{
this.name=name;
this.age=age;
this.email=email;
}
}

 
Didn't find what you were looking for? Find more on can somebody please explain the function of "this" Or get search suggestion and latest updates.




Tagged: