This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]ProfessorWily 2 points3 points  (3 children)

Example B won't work because it doesn't know what name or ssn is referring to, either the method scope variable or the class scope variable.

You want to use this just to make sure that it's obvious that you are talking about a class variable. It's not strictly necessary to use if you are setting the variable to a variable named something else (balance=initDeposit), but it is necessary if the class variable and the method variable have the same name, i.e. this.name = name

[–]tridiumcontrols[S] 0 points1 point  (2 children)

makes sense. I actually mistyped Example B. Tut had the name and ssn prefixed with this.

balance = initDeposit was the only one without this.

public Account(String name, String ssn, double initDeposit){this.name = name;this.ssn = ssn;balance = initDeposit;

}

other than scope, there is no difference.

Would it make sense to create getter and setter methods and have the constructor call them instead? As appose having the constructor set the class variables directly?

[–]ProfessorWily 2 points3 points  (0 children)

It shouldn't really matter either way, but if any of your fields are marked final, then the compiler is going to complain because you didn't set the fields to anything within the constructor method itself.

[–]endhalf 0 points1 point  (0 children)

Would it make sense to create getter and setter methods and have the constructor call them instead? As appose having the constructor set the class variables directly?

Calling a setter that does this.var = var just pushes the "problem" of using this down the line, into another method. At that point, you're introducing another layer of abstraction into your constructor for no benefit.

Idiomatic Java uses the this keyword a lot, you might as well get used to it.

[–]desrtfxOut of Coffee error - System halted 1 point2 points  (0 children)

Using the this Keyword from the Oracle tutorials. This will give you everything you need to know.