简体   繁体   中英

Having trouble calling a boolean method into another class

I'm having trouble calling a boolean method into another class. Whatever I try, either the program can't find the variable, or warns me about trying to use a non-static variable in a static context.

The boolean code I am trying to access

public boolean isSame(String title, String author)
{
    return this.title.equals(title) &&
           this.author.equals(author);
}

The (current) code I'm using to access the method (I know it's wrong)

public void copyCount(String title, String author)
{
    int numberOfCopy = 0;
    boolean Book.isSame = false;
        if(isSame == true) {
            numberOfCopy++;
        }  
    System.out.println(copyCount);
}

Essentially, the copyCount method (from the 'Library' class) is supposed to take 2 String parameters and test them using the isSame method (from the 'Book' class). isSame returns true if the books details match the given ones, and false if they do not.

How do I properly reference the isSame method from another class? Thanks.

How do I properly reference the isSame method from another class?

It looks like you need an instance of the Book class...

Book book = new Book("myTitle", "myAuthor");  // I'm just guessing there's a constructor like this
boolean same = book.isSame("anotherTitle", "anotherAuthor");
// 'same' will be false

If your both methods are in different classes.

You can only access the static method without creating the object of the class. If your isSame method is static then you can access is by using the Book.isSame(), but if your isSame method is not static then you need to create a object of Book class and then access the isSame method using that object.

See the code below:

Book book = new Book();
boolean result = book.isSame("title","author");

Pass the variables in constructor if you have. By the way the code is just a example to show the flow.

Earlier answers may be correct by the requirements , but what this sounds like is the need for an equals method.

By convention, Java objects all have an equals method, and it should be overridden when you wish to determine the equality of two objects. Here, since you're attaching String s to equality, it can be tougher to infer that equality is what you were really looking for.

Here's an example:

public boolean equals(Book other) {
    return null != other && this.title.equals(other.title) &&
       this.author.equals(other.author);
}

You'd need to modify your copyCount method to take an instance of Book instead of author and title , but it'd be an overall better design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM