Hi all,

I am currently attempting my first project for programming using Java.
One of the classes I have made contains 3 constructors, now I remember learning a little about the this keyword and thought it may be appropriate here, however, I am not completely sure on how to use it. I will try and find some examples on the net to figure it out, but firstly I would like to ask you for your opinion on whether or not to use the this keyword for the following constructors:

public class Order {
    String productName;
    String message;
    double price;
    double discount;
    double total;
    int quantity;
    boolean isDiscounted = false;
    boolean isValidOrder = true;
    static int orderNum = 0;




public Order(){//constructor 1
        orderNum++
        isValidOrder = false;
        message = "ERROR:  You have not specified any parameters for the order.";
    }
    public Order(String n, double p, int q){//constructor 2
        orderNum++
        productName = n;
        price = p;
        quantity = q;
    }
    public Order(String n, double p, int q, double d){//constructor 3
        orderNum++
        productName = n;
        price = p;
        quantity = q;
        isDiscounted = true;
        if ((d >= 1) && (d <= 100)){
            isValidOrder = true;
            discount = d;
        }
        else{
            isValidOrder = false;
            message = "ERROR:  The discount value: " + d + " is not valid";
        }
    }

unfortunately my course module only had one simple example using the this keyword so if you feel like giving me a tip or a link to a similar example, it would be much appreciated (and save me some time searching :))

thank you

Here's a basic tutorial on the this keyword: http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html

For your current code, I would try using this in the third constructor. You've intialized the variables productName, message, price, discount, total, and quantity in your constructors but I would initialize them before actually putting them in the constructors. For example for productName I would do String productName = ""; right before I start using them in my constructors.

Edited 5 Years Ago by Chronister: n/a

thanks for that Chronister,

I am glad you brought up the question of initializing the variables because I had discussed this with one of the instructors and he informed me (it also states in my module) that it was not compulsary to intitialize them as they would be autimatically assigned to their default values. But I take it from your comment that it is indeed better practice to do it, thank you kindly I find it very helpful to learn from other people other than just through the course.

this keyword always points to the current object.So when you have to use two different variables of the same name that time this keyword is used

This article has been dead for over six months. Start a new discussion instead.