-1

I had a question about using "this" for classes with methods. Here is a snippet of code I wrote that is giving me an error. I am confused about how to use class non-static class methods while referencing the object using "this". Can someone please help me?

update, here is all my code

public class customer
    {
public String name;
public String accountID;
public String address;
public String creditCardNumber;
public String password;
public book[] bookArray;
public int numBooks;

public String toString(){
    return "Customer name: " + this.name + " Customer account ID " + this.accountID
    + " Customer address: " + this.address;
}

public String getName(){ //getter method for customer name
    return this.name; 
}

public String getAccountID(){ //getter method for cutomer accountID
    return this.accountID;
}

public String getAddress(){ //getter method for customer address

    return this.address;
}

public String getCreditCardNumber(){ //getter method for customer creditCardNumber
    return this.creditCardNumber;
}

public String getPassword(){ //getter method for customer password
    return this.password;
}

public void setPassword(String Password){ //setter method for customer password
    Password = password;
}

public void setAddress(String Address){ //setter method for customer address
    Address = address;
}

public void setCreditCardNumber(String CreditCardNumber){ //setter method for customer creditCardNumber
    CreditCardNumber = creditCardNumber;
}

public customer(){ //constructor method for customer class
    this.name = name;
    this.address = address;
    this.accountID = accountID;
    bookArray = new book[500];
    numBooks = 0;
}

public void addBook(book currentBook){ //addBook method, adds current book to bookArray and adds one to numBooks int
    bookArray[numBooks] = currentBook;
    numBooks++;

}


}

Basically I am trying to have the method take the current book object and pass it through the addBook method which is in the customer class which then adds that object to an array. What is the best way to do this?

public class book
{
public String idNumber;
public String title;
public String author;
public String publisher;
public String yearOfPublication;
public int inStock;
public int sold;
public int price;

public String toString(){
    return "Book ID Number: " + this.IDNumber+ " Book Title " + this.bookTitle + " Book Author: " + this.bookAuthor //toString method that returns all info for book class
    + " Book Publisher: " + this.bookPublisher + " Year of Publication: " + this.yearOfPublication; 
}

public String getIDNumber(){ //getter method for book idNumber
    return this.idNumber;
}

public String getTitle(){ //getter method for book title
    return this.title;
}

public String getAuthor(){ //getter method for book author
    return this.author;
}

public String getPublisher(){ //getter method for book publisher
    return this.publisher;
}

public String getYearOfPublication(){ //getter method for book yearOfPublication
    return this.yearOfPublication;
}

public int getBooksInStock(){ //getter method for book inStock
    return this.inStock;
}

public int getBooksSold(){ //getter method for book sold
    return this.sold;
}

public int getBookPrice(){ //getter method for book price
    return this.price;
}

public void bookSales(int numBooksRequested){ //method  records sale of book to customer object
    if(inStock == 0){ //checks if book is out if stock, if so prints error message
        System.out.println("Error, " + book.getTitle() + " is currently out of stock.");        
    }
    else if(numBooksRequested > inStock){ //checks if amount of book requsted is greater than whats in stock, if so prints error message
        System.out.println("Error, you have requested more copies of " + this.book.getTitle() + " than is currently in stock");
    }
    else if(numBooksRequested < 0){ //checks if amount requested is less than 0, if so prints error message
        System.out.println("Error, invalid amount");
    }
    else{
        for(int i=0; i<numBooksRequested; i++){ //loops through until the total number of the book ordered is passed through the addBook method
            customer.addBook(this.book); //if amount requested is valid, utilizes addBook method to add current book object
            inStock = inStock - 1;
        }
    }

}

public book(String IDNumber, String Title, String Author, String Publisher, String YearOfPublication, int Price){
    IDNumber = idNumber;
    Title = title;
    Author = author;
    Publisher = publisher;
    YearOfPublication = yearOfPublication;
    Price = price;
}

public void reStockBook(int bookRestock){
    if(bookRestock < 1){
        System.out.println("Error, Invalid Number");
    }

    else{
        inStock = inStock + bookRestock;
    }

}

}
biglemon29
  • 35
  • 7
  • Can you be more explicit where the error is? Also show the definitions for all fields in the class, that will be relevant. – markspace Mar 20 '20 at 20:48
  • 4
    book.this.book is not valid. `this` must always be in front. – ControlAltDel Mar 20 '20 at 20:48
  • @markspace Hi for the this.book.getTitle() I am getting a "cannot find symbol - variable book" error – biglemon29 Mar 20 '20 at 20:52
  • @biglemon29 because you don't have a property named book. you should share a full example – lainatnavi Mar 20 '20 at 20:53
  • 1
    You really don't need to use `this` to dereference an instance field unless there is ambiguity between like named values. – WJS Mar 20 '20 at 21:08
  • @WJS and that's not the main reason for `this` to exist, as one could easily avoid using the same name for the member and the variable being passed to a method. The main reason for `this` is the ability of an object to reference itself. – lainatnavi Mar 20 '20 at 21:24
  • @lainatnavi "*and that's not the main reason for this to exist,*" FIrst, I never said or even implied that. Second, please cite the paragraph and section where the Java Language Specification says that because I could not find it. – WJS Mar 20 '20 at 21:36
  • @WJS didn't intend to disapprove your comment but rather to extend it, since the first example people bring about the this keyword is the differentiation of the parameter name from the class member name. The JLS doesn't say that, but I think it's inappropriate to start talking about `this` by saying what it's used for prior to explaining what it IS in the first place. – lainatnavi Mar 20 '20 at 22:03

3 Answers3

1

this is used to differentiate variables and methods in the object itself, rather than parameters or superclass variables

public class Example {
  private int book;
  public void foo1() {
    book; // this is the object's book;
    this.book; // this is the same as the above
  }

  public void foo2(int book) {
    book; // this is the method parameter book;
    this.book; // this is the object's book;
  }
}
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • It would be better to say that this "is a reference to the object for which the instance method or default method was invoked, or to the object being constructed." That one usage (among others) then becomes a natural consequence of the definition. – lainatnavi Mar 20 '20 at 21:14
1

this is used to refer to variables in that class/instance, the usual way is for setters ie

String info;

public void setInfo(String info)
{
    this.info = info;
}

This ensures that the instance variable info is set from the info in the method and not just setting the passed in variable to itself.

you have book.this.book this is not correct as this cannot have anything before it so it should be this.book. To reference a static variable you do not use this but the class name.

ie this.book (concrete class) or Book.book (static)

Theresa Forster
  • 1,914
  • 3
  • 19
  • 35
1

It depends on where bookSales() is at. I'm going to guess that you have something that looks like this, but with way more extraneous comments:

class Book() {

    private final String bookTitle;
    private int inStock;

    public String getTitle() { return this.bookTitle; }

    public int getQuantity() { return this.inStock; }

    public void bookSales(int numBooksRequested) { 
        if (this.inStock == 0) { 
            System.out.println("Error, " + this.book.getTitle() 
                    + " is currently out of stock.");           
        } else if (numBooksRequested > this.inStock){ 
            System.out.println("Error, you have requested more copies of " 
                    + this.getTitle() + " than is currently in stock");
        } else if (numBooksRequested < 0){ 
            System.out.println("Error, invalid amount");
        } else {
            for (int i = 0; i < numBooksRequested; i++) { 
                customer.addBook(this); 
                this.inStock = this.inStock - 1;
            } // Wouldn't this.inStock -= numBooksRequested make more sense?
        }
    }

    public Book(String title, int quantity) {
        // TODO: Check quantity's not negative, throw exception if it is
        this.bookTitle = title;
        this.inStock = quantity;
    }

}

Let's say that in a different class you have

Book bible = new Book("The Holy Bible", 70000);
Book bobsRules = new Book("Robert's Rules of Order", 538);

That lines calls the constructor, and "The Holy Bible" gets put in bible.bookTitle and 70,000 gets put into bible.inStock. Likewise for Robert's Rules of Order. Only those are presumably private properties. I'm assuming you're providing getters, so that's what's used outside of the Book class to access those properties.

As you write the Book constructor, getters, setters, etc., you have no idea what identifiers are going to be used for the various books. And the authors of the Java language specification don't expect you to. Hence the reserved keyword this, which at runtime might refer to bible or to bobsRules or to books we don't even know about.

Outside of the Book class, you use the instance identifiers. For example:

bible.bookSales(616);
bobsRules.bookSales(197);

In what I've written, customer is undefined. How is customer defined in your project? Maybe bookSales() should take a Customer customer parameter...

Regardless, bookSales() doesn't have to call this.getTitle(), it can access this.bookTitle directly. The performance improvement is practically trivial, however.

Part of the confusion might be because "this." is not strictly required. If you indeed have inStock as a property of Book, then you can address it just the same as "this.inStock" as just "inStock".

Do pay attention to your IDE's syntax highlighting (IntelliJ with light color scheme tends to be more readable than InteillJ with the dark color scheme, in my opinion).

I see other problems in what you've posted, but those don't directly pertain to your question, so I won't address them.

Alonso del Arte
  • 1,005
  • 1
  • 8
  • 19