有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java将“this”与非静态方法结合使用

对于将“this”用于带有方法的类,我有一个问题。下面是我编写的一段代码,它给了我一个错误。在使用“this”引用对象时,我对如何使用类非静态类方法感到困惑。有人能帮我吗

更新,这是我所有的代码

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++;

}


}

基本上,我试图让该方法获取当前book对象,并通过customer类中的addBook方法将其传递,然后将该对象添加到数组中。最好的方法是什么

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;
    }

}

}

共 (3) 个答案

  1. # 1 楼答案

    这用于引用该类/实例中的变量,通常的方法是针对setter ie

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

    这确保了实例变量info是从方法中的info设置的,而不仅仅是将传入的变量设置为自身

    你有一本书。这这本书是不正确的,因为它前面不能有任何东西,所以它应该是这个。书要引用静态变量,您不使用该变量,而是使用类名

    这个。书(具体类)或书。书籍(静态)

  2. # 2 楼答案

    这取决于bookSales()的位置。我猜你有这样的东西,但有更多无关的评论:

    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;
        }
    
    }
    

    假设你在另一个班上

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

    这行代码调用构造函数,“圣经”被放入bible.bookTitle,70000被放入bible.inStock。罗伯特的《秩序规则》也是如此。只有那些大概是私人财产。我假设您提供了getter,所以在Book类之外使用它来访问这些属性

    在编写Book构造函数、getter、setter等时,您不知道各种书籍将使用什么标识符。Java语言规范的作者并不期望您这样做。因此,保留关键字this,在运行时可能会引用biblebobsRules或我们甚至不知道的书籍

    Book类之外,使用实例标识符。例如:

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

    在我写的文章中,customer是未定义的。在您的项目中customer是如何定义的?也许bookSales()应该采用Customer customer参数

    无论如何,bookSales()不必调用this.getTitle(),它可以直接访问this.bookTitle。然而,性能改进实际上微不足道

    部分混淆可能是因为“this.”不是严格要求的。如果您确实将inStock作为Book的属性,那么您可以将其与“this.inStock”一样处理为“inStock

    一定要注意IDE的语法突出显示(在我看来,带浅色方案的IntelliJ比带深色方案的IntelliLJ更容易阅读)

    我在你的帖子中看到了其他问题,但这些问题与你的问题没有直接关系,所以我不会解决它们

  3. # 3 楼答案

    this用于区分对象本身中的变量和方法,而不是参数或超类变量

    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;
      }
    }