1

I'm new to programming, this is one of our first object oriented programs that we are doing in class. I feel like I have used "this." more than I need to, but my program works properly and I get the correct output. In my getters, can I return the variable without using this? I guess my question is does this.variablename refer to the parameter variable or the data field declared at the top of my class?

import java.util.Date;

public class Account{

    private int id = 0;
    private double balance = 0;
    private static double annualInterestRate = 0.00;
    private Date dateCreated;

    public Account(){}

    public Account(int id, double balance){
        this.id = id;
        this.balance = balance;
    }

    public int getId(){
        return this.id;
    }

    public void setId(int id){
        this.id = id;
    }

    public double getBalance(){
        return this.balance;
    }

    public void setBalance(double balance){
        this.balance = balance;
    }

    public double getAnnualInterestRate(){
        return this.annualInterestRate;
    }

    public void setAnnualInterestRate(double annualInterestRate){
        this.annualInterestRate = annualInterestRate;
    }

    public Date getDateCreated(){
        return this.dateCreated = new Date();
    }

    public double getMonthlyInterestRate(){
        return (this.annualInterestRate / 12);
    }

    public double getMonthlyInterest(){
        return ((this.annualInterestRate / 100) / 12) * this.balance;
    }

    public void withdraw(double amount){
        this.balance -= amount;
    }

    public void deposit(double amount){
        this.balance += amount;
    }

}

Here is my main method and test class:

public class AccountTest{

    public static void main(String[] args){

        Account myObject = new Account(112233, 20000.00);
        myObject.setAnnualInterestRate(4.5);
        myObject.withdraw(2500.00);
        myObject.deposit(3000.00);

        System.out.printf("The account balance is $%,.2f.", myObject.getBalance());
        System.out.printf("\nThe monthly interest is $%,.2f.", myObject.getMonthlyInterest());
        System.out.print("\nThe account was created at " + myObject.getDateCreated());   
    }  
}
  • 1
    What happened when you tried it? Exactly what do you think *may* be wrong with your use of `this`? – Elliott Frisch Oct 02 '15 at 23:29
  • this.somevariable refers to a member of the instance of the class. – bhspencer Oct 02 '15 at 23:30
  • 1
    `private static double annualInterestRate = 0.00;` <-- static is wrong there, FWIW. It will "work" (as in, compile) but cause bizarre behavior when a different interest rate is set for different instances. See http://stackoverflow.com/questions/11579953/static-fields-on-a-null-reference-in-java for why is allowed, although confusing. – user2864740 Oct 02 '15 at 23:36
  • @bhspencer Except in the case of `this.annualInterestRate` (a static variable not associated with an instance), where it does not.. – user2864740 Oct 02 '15 at 23:37
  • Is this.variable referring to the variable getting passed in parameters of my class methods? Or is it referring to the data field at the top? – JakeFromStateFarm Oct 02 '15 at 23:38
  • If the question is about whether `this` is always necessary when you refer to a field, the answer is no. Think about variable names as given names and `this` as a family name. If there's only one variable in scope with a given name, you can use the simple name or you can prefix it with `this.`. In these cases it's a question of style. But if you have a parameter/local variable in scope with the same name as a field (like you typically do in setters), you **must** use `this` when referring to the field, just like you'd use people's full names when there are two Johns in the same room. – biziclop Oct 02 '15 at 23:38
  • @user2864740, The program instructions told us to create "A private static double data field named annualInterestRate that stores the current interest rate (default 0). Assume all accounts have the same interest rate." – JakeFromStateFarm Oct 02 '15 at 23:40
  • @user3686567 In that case, I would make `getInterestRate` and `setInterestRate` static as well, and access all static methods/properties *without* using `this.` in `this.somethingStatic`, as such is confusing because something static does not belong to any instance.. – user2864740 Oct 02 '15 at 23:41
  • Thanks you guys! I really appreciate everything. We are moving on to inheritance and polymorphism next week, should be quite a challenge -_- – JakeFromStateFarm Oct 02 '15 at 23:51

5 Answers5

4

Have I used the this keyword correctly in my class?

Yes. It is not incorrect to use this when it is strictly unnecessary. Some people would argue that it makes the intent more clear. Either way, it is a stylistic decision.

In my getters, can I return the variable without using this?

Yes.

I guess my question is does this.variablename refer to the parameter variable or the data field declared at the top of my class?

this.name refers to a field NOT a parameter.

name could refer to either a parameter or a field. If there is an (in-scope) parameter and a field with the same name, it will refer to to parameter. Hence if you wrote:

public void setId(int id){
    id = id;
}

you would simply be assigning the value of the parameter id to itself. The "fix" for my broken setId method is to either use this or change the name of the parameter; e.g. make it newId.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Thanks Stephen. I was just kind of confused on whether it referred to the parameter or data field. I just removed it from all of my getters and the program still works properly. – JakeFromStateFarm Oct 02 '15 at 23:49
0

(this) can be used inside method or constructor of class. (this) works as a reference to current object whose method or constructor is being invoked. this keyword can be used to refer any member of current object from within an "instance method" or a "constructor".

Aven
  • 72
  • 10
0

The analogy I use is that the code you're writing is going to be a script, like that for a play, that gets handed out to all the actors (the objects). The actors all play different roles (like classes), and so they're going to be capable of doing various things at the behest of the director. So when code is being executed, that's usually in the context of some instance. You can explicitly tell an actor to refer to themselves with the keyword this (e.g. this.id).

Most of the time, you won't need to use the keyword this, because the code won't be ambiguous (we'll all know what the actor is talking about if she just says ID). BUT you have there an example of this being necessary; when you have local variables/method parameters with the same name as a field, that variable is said to shadow the field. This is fine! You just need to use this.variable to refer to field, and variable to refer to the local within that context.

The other use for this which you haven't touched on in the use of this to call the objects own constructor; an 'explicit constructor invocation'. For example, your currently empty Account() method could instead contain the statement this(100, 0);, so as to call the other constructor method with two parameters.

Source: here.

Luke
  • 1,724
  • 1
  • 12
  • 17
  • Thank you for the analogy Luke! That is a good way to think about it. I understand now that since I am using the same variable names I have to distinguish, I just wasn't sure that it referred to the class or parameter being passed. Thank you sir. – JakeFromStateFarm Oct 02 '15 at 23:56
0

In your getters you can omit using this, it'll still work because there're no local variables with the same name.

You shouldn't use this to access a static variable. The correct way to access annualInterestRate is to specify the class first. eg: return ((Account.annualInterestRate / 100) / 12) * this.balance;

Kurumi
  • 103
  • 5
0

Your code will work correctly but you are overuse this keyword, The correct usage of this keyword in your example

import java.util.Date;

public class Account {

    private int id = 0;
    private double balance = 0;
    private static double annualInterestRate = 0.00;
    private Date dateCreated;

    public Account() {
    }

    public Account(int id, double balance) {
        this.id = id;
        this.balance = balance;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public double getAnnualInterestRate() {
        return annualInterestRate;
    }

    public void setAnnualInterestRate(double annualInterestRate) {
        this.annualInterestRate = annualInterestRate;
    }

    public Date getDateCreated() {
        return dateCreated = new Date();
    }

    public double getMonthlyInterestRate() {
        return (annualInterestRate / 12);
    }

    public double getMonthlyInterest() {
        return ((annualInterestRate / 100) / 12) * balance;
    }

    public void withdraw(double amount) {
        balance -= amount;
    }

    public void deposit(double amount) {
        balance += amount;
    }

}

don't overuse this keyword, use it in the scope if they are another variable with the same name and you need to use fields related to this object for instance functions not static one.

Ahmad Al-Kurdi
  • 2,248
  • 3
  • 23
  • 39