I have a question regarding this in the following code. In the following, this.name will set the name. We could also do this using name = name, so my question is should the this pointer be used. This is not an homework
import java.io.*;
public class Employee{
String name;
int age;
String designation;
double salary;
//This is the constructor of the class Employee
public Employee(final String name){ //EDIT: Made parameter final
this.name = name;
//name= name; this is also correct
}
//Assign the age of the Employee to the variable age.
public void empAge(int empAge){
age = empAge;
}
//Assign the designation to the variable designation.
public void empDesignation(String empDesig){
designation = empDesig;
}
//Assign the salary to the variable salary.
public void empSalary(double empSalary){
salary = empSalary;
}
//Print the Employee details
public void printEmployee(){
System.out.println("Name:"+ name );
System.out.println("Age:" + age );
System.out.println("Designation:" + designation );
System.out.println("Salary:" + salary);
}
}
// name= name; this is also correct
This is not correct. It'll assign your parameter to itself. By using the this keyword, you're declaring which name you're using (i.e. the field on your Employee object).
You may wish to name the field differently from the parameter. However this means that all works well until someone automatically refactors your code to (perhaps inadvertently) declare the field and parameter as the same name!
For this reason you'll often see method signatures defined thus:
public Employee(final String name)
The final keyword prevents reassignment, and stops you from mistakenly reassigning the input parameter, and consequently not assigning to your field. Note also that if you declare the field as final, then compilation will fail if you don't make an assignment to that field. Using final is a good way to trap such errors and also enforce the immutability of an object (often a good thing - it contributes to a more reliable solution, especially in a threaded environment).
Well to avoid the confusion in cases like u mentioned name=name we uses this pointer to make it clear the we here mean class variable name .
So to make understand the reader here in this case we use this though there can be many other cases where (this) is more useful.
In some compilers name=name gives error as well
Notice that there are two things called name in your code. Your class Employee has member variable called name, and the constructor takes a parameter that's also called name.
What you want to do in the constructor is set the member variable name to the same value as the parameter name. To access the member variable, you have to use this.name, because name refers to the parameter - because the variables have the same name, the parameter is hiding the member variable.
Note that name = name; does not do the same thing as this.name = name;.
When you do name = name;, you assign the value of the parameter name to the parameter itself - not to the member variable. The compiler does not magically know that the first name is supposed to mean the member variable, and the second name is supposed to mean the parameter.
So, you need this in this case to refer explicitly to the member variable, instead of the parameter that is hiding the member variable.
In this case this is just a scope resolution/disambiguation.
public Employee(String name){
this.name = name;
// the above line will assign a value of parameter to instance variable
// name= name; this is also correct
// (**NO** the above line will assign a value of parameter to itself)
}
When the parameter name and your class variable names are same, then to differentiate between them, you write this.classVariable to identify the class variale
When you call a variable, the pointing one is the one who is the closest to your current scope.
So, if program is currently containing in memory a local variable toto and the wrapping class containing a field variable toto, you have to precise this keyword in order to access the field's one.
Otherwise, the field variable is said to be shadowed by the local variable and so doing toto = toto assigns the local parameter to itself (never useful) and not what you are expecting => the field variable.
Why make it so hard on yourself?
Just rewrite the signature/method like this:
public Employee(String _name) {
name = _name;
}
Always try to avoid variable hiding or other hard-to-read constructs. If you want your code to be maintainable, write it in such a way that everybody can understand it immediately. Even if you are the only one; you might forget what you meant in time.
This Keyword Program
public class ThisKeywordActivity extends Activity {
int a=20;
public ThisKeywordActivity(int a) { // this();
//this.a = a;
}
public ThisKeywordActivity()
{
System.out.println(" msg default Constructor ");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_this_keyword);
ThisKeywordActivity thisKeywordActivity2 = new ThisKeywordActivity(100);
thisKeywordActivity2.show(40);
}
public void show( int a)
{
System.out.println("msg a 2==="+a);
System.out.println("msg a 3==="+this.a);
}
}
Output
a2=40
a3=20
Related
This question already has answers here:
When should I use "this" in a class?
(17 answers)
Closed 2 years ago.
I'm very new to JAVA and trying the following code to initialize the values of object variable using constructor:
public class Javaprog {
int rollnumber;
String name;
Javaprog(int rollnumber, String name) {
rollnumber = rollnumber;
name = name;
}
public static void main(String[] args) {
Javaprog student1 = new Javaprog(12, "Simon");
System.out.println(student1.rollnumber);
System.out.println(student1.name);
}
}
I want to understand why the code above returns the default values of rollnumber and name(0 and null), unless I use "this" to reference the variables inside the constructor like below:
this.rollnumber = rollnumber;
this.name = name;
I'm aware this refers to the current object, but my point is when the constructor runs for creation of an object, does it not understand by default that these variables relate to the object being created .
Is it that, without the use of this keyword they are just "class variables" and don't attach to the object being created.
Found a similar Q here, but did not fully understand the mandate to use this:
java this keyword inside constructor
let’s keep constructors aside and just look at it from a code point of view.
the parameters rollnumber and name are local variables, their scope is only in the function. So when you say
rollnumber = rollnumber;
It simply assigns the current value of local variable rollnumber to itself (does nothing). There is no way to differentiate rollnumber (the parameter/loca variable inside the function) and the instance variable, rollnumber.
To make sure the compiler understands what we want, we use
this.rollnumber (referring to instance variable) = rollnumber (parameter);
To avoid this, you can name your instance variable something else, like rollnum. This way the compiler will search for rollnum in the local scope (meaning within the constructor function, not found) then in the higher scope, where it will be found as an instance variable and correctly assigned.
rollnum = rollnumber;
will work.
I am staring to study java and currently I am learning about the classes setters.
I see that the most common way to make a setter is something like this.
class Apple{
private String _name;
//Setters
public void setName(String name){
_name = name;
}
}
I am used to C so this code raises me a question. If I am setting _name = name in a function, after this function is completed and his stack is discarded why does the variable _name still stores the right value? This is confusing because in C if I assig a pointer to another pointer inside a function like this it would probably cause a segmentation fault (since name is a temporary variable).
In Java, you as an user don't have control over the stack as in C/C++ languages.
In addition, all non-primitive data types (int, double, etc.) are stored in the heap. The user is only able to use references or pointers and is not required to perform any kind of memory management, since a mechanism known as garbage collector already frees those instances which haven't any reference to them. Therefore, there are no such thing as pointers in Java, although you can assign a null value to a non-primitive variable: Foo f = null;
Therefore, in Java you could literally behave what this C++ code does:
class Foo {
Foo( int a ) {}
};
void bar( int a ) {
Foo f(a); // f is placed in the stack
}
The only way you can create an instance of Foo in java would be like this:
void bar( int a ) {
Foo f = new Foo(a); /* f is a reference to the new instance
* (placed in heap) */
}
Actually, name is an instance variable and setName() is an instance method. This means that there is a separate copy of name for every object of the class Apple. The setName() method sets the value for the global variable of the object it is called with to that of its argument. So, even after the stack of the method is discarded, the object exists and so does the value of this object's copy of name. See this example below:
class Apple {
private String name; //instance variable
public void setName(String name) {
this.name = name; //same as what you have written
}
//main method
public static void main(String[] args) {
Apple obj = new Apple(); //object created
Apple obj2=new Apple();
obj.setName("Yolo");
obj2.setName("Yay!");
System.out.println(obj.name); //displays obj's copy of name that holds the value "Yolo"
System.out.println(obj2.name); //displays obj2's name
}
}
This displays
Yolo
Yay!
I hope this makes it clear to you.
You are setting the reference of name to the reference of _name so they look in the same spot in memory. Therefore when the instance of setName disappears and the variable name with it the reference stored in _name remains.
Since you set _name to private it can only be accessed inside the class Apple. You cant change it within your main method and that's why you create the set method so it can be changed by outside classes (I.e. Your main method)
I have two classes. Both of them refer to the same variables inside the constructor. I am confused, when I used this.name I don't need to change the name of the parameter, the Java compiler knows that I am referring to the main variable?
On the second class example, the parameters name was changed but it is not using this.
What is the different between these two classes?
Are they both considred "good programming" ?
class Account {
private string name;
private int amount;
Account(String name, int amount) {
this.name = name;
this.amount = amount;
}
}
class Account {
private string name;
private int amount;
Account(String n, int a) {
name = n;
amount = a;
}
}
In this case Account(String name, int amount) if your code says name = "ABC";, it is setting the parameter name, not the member. If you want to set the member, you need you reference it via this.name.
So name = name; does nothing (sets the parameter to itself). this.name = name; sets the member to the parameter.
Both of your codes are not wrong.! But, In Java it's considered poor practice to use meaningless name prefixes or suffixes to distinguish instance variables from parameters from local variables. I would like to recommend to use whatever names make the code easiest to understand.
Java allows to use same name for instance variable and local variable/parameter.
When method/constructor parameter name is same as instance variable name then we need to explicitly use this keyword to inform JVM that we are trying to use this instance variable; not local variable. Otherwise, for same named variables without this JVM selects more specific scope variable.
For first case you are using same variable name for parameter and instance variable called name so you need to explicitly define which one is your instance variable using this as bellow:
this.name = name;
For second case, there is no naming confusion so if you don't use this there is no problem to identify instance variable.
N.B.
It is better to use this for readability when you are accessing instance variables.
Either are fine. You would only use this.name if you wanted the private instance variable to also be called name. When you have an instance variable that is a different name than the parameter taken in, it does not matter.
What's the different between this two classes?
Functionally none. Compiler will change your 2nd example as follows:
Account(String n, int a)
{
this.name = n;
this.amount = a;
}
Are both ways consider "good programming"?
I prefer 1st way to write code.
I need to create 10 objects from my Variable Class but I'm getting errors.
Here is my code:
for(n=1;n<10;n++){
variableTab[n]= "variable" +""+n;
Variable variableTab[n] = new Variable();
//System.out.println(variableTab[n]);
}
And the errors I have:
Type mismatch: cannot convert from Variable to Variable[]
Syntax error on token "n", delete this token
Duplicate local variable variableTab
I don't know where is the problem because variableTab[] is a String Tab.
You are trying to assign data to an object that hasn't been created yet. Also, you shouldn't start at index 1. Arrays begin at index 0, so essentially, you are robbing yourself of extra space and making things harder on yourself by doing that. This also means that you are creating 9 objects, not 10. Use the implementation below.
Variable [] variableTab = new Variable [10];
for(n=0;n<10;n++){
variableTab[n]= "variable" +""+n;
//System.out.println(variableTab[n]);
}
Update per comments:
If you are trying to store the name of a object, you need to create a member variable to store that name in.
public class Variable {
private String name; //This will be used to store the unique name of the object
//Default constructor for our class
Variable () {
name = "";
}
//Constructor to initialize object with specific name
Variable (String name) {
this.name = name;
}
//We need a way to control when and how the name of an object is changed
public setName (String name) {
this.name = name;
}
//Since our "name" is only modifiable from inside the class,
//we need a way to access it from the program
public String getName () {
return name;
}
}
This would be the proper way to setup a class. You can then control the data for each class in a more predictable way, since it is only able to be changed by calling the setName method, and we control how the data is retrieved from other sections of the program by creating the getName method.
You might want to initialize your object first. If it is an array of objects that you're trying to create, do it this way:
Variable[] variableTab = new Variable[n];
You're trying to assign values to something that hasn't been created yet!
You're code should look like:
for(n=0;n<10;n++){
Variable variableTab[n] = new Variable();
variableTab[n]= "variable" +""+n;
//System.out.println(variableTab[n]);
}
Basically, you're trying to assign a value to something that doesn't exist yet.
I'm trying to understand the this keyword in java. I wanted to rewrite this code by using the this keyword instead. Please let me know if I've done it right. Here's the original code:
public class Book {
private String title;
private String author;
private String publisher;
public Book(String bookTitle, String authorName, String publisherName){
title = bookTitle;
author = authorName;
publisher = publisherName;
}
}
And here's the re-written code:
public class Book {
private String title;
private String author;
private String publisher;
public Book(String title, String author, String publisher){
this.title = title;
this.author = author;
this.publisher = publisher;
}
}
Have I done it correctly?
Thanks,
Kevin
EDIT: Thanks for the responses... one more question: in the constructor of the revised code, which side of the equals sign refers to the class variables? For example, in this.title = title;, does this.title refer to the title variable from the constructor or from the class variable?
Based on the responses below, I think the answer is this.title refers to the class variable title.
Yes. The this keyword means "the instance of this class that I'm running inside right now". You usually don't need it for variable or method references, but in this (common) case where the constructor parameters have the same name as the fields they're being saved in, using this distinguishes to the compiler between the fields and the parameters.
You've used this correctly.
Now, to understand why this works this way notice that the local variable (constructor parameter) names in your previous version of the constructor are different than your class member names. Hence, this wasn't required since there wasn't any ambiguity.
In the second version, since, their names are the same the constructor parameters over shadow or hide the class member fields within the constructor body. Hence, this which points to the current object instance is required to refer to them explicitly.
Also note that this cannot be used from a static context (block or a static method) for the obvious reason that no current object instance is associated with it. It must be used from inside a constructor, instance block or an instance method.
From HERE
The most common reason for using the this keyword is because a field
is shadowed by a method or constructor parameter.
Lets take an example which illustrates what above statement means. I have added comments at appropriate section of code for your reference.
public class ThisKeywordExample {
private int x;
private int y;
public void setVar(int x, int y) {
x = x; // Setting private variable x value
y = y; // Setting private variable y value
System.out.println(x + " " + y); // prints 10 20
}
public static void main(String[] args) {
ThisKeywordExample obj1 = new ThisKeywordExample();
obj1.setVar(10, 20);
System.out.println(obj1.x + " " + obj1.y); //prints 0 0 because the effect is limited to the local copies of x & y in the setVar method
}
}
Now I would suggest you change setVar method to
public void setVar(int x, int y) {
this.x = x; // Setting private variable x value
this.y = y; // Setting private variable y value
System.out.println(x + " " + y); // prints 10 20
}
and see how it works now.
"this" allows you to easily distinguish between variables of the same name within a class/object.
It appears to me that you have used "this" correctly.
I would, however, caution from using the same variable names for multiple uses. In this situation, it is acceptable; however it would be wise to avoid getting into bad programming habits.
Yes you have understood this in java correctly. From Sun's original documentation:
Within an instance method or a constructor, this is a reference to the
current object — the object whose method or constructor is being
called. You can refer to any member of the current object from within
an instance method or a constructor by using this.
Source: http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
look in your Question there are two big concepts of using this has evolved.
In the 1ST and foremost case this is used to refer to the current object which has evolved that constructor means this carry a referenceid of current object....
In the 2nd case this is used primarly to distinguish between the local parameters and instance variables because the name of both variables types are same....and it is a rule in java that local variable overshadow the instance variables(of same name) when used in any local block or method...so here this differentiates between the instance variable(this.title) and local variable(title)..
And remember this lets u refer directly to the object you can use it to avoid any name space collisions that may ocuur between instance and local variables...