Search code examples
javagetter-setterbluej

Java: Accessing different variables in a different class to be used within a conditional statement


I have done some research on the forums and found this to be most applicable my question but the solution doesn't work: accessing a variable from another class

So I am trying to access two variables in my "LibraryCard" class:

    private int limit;
    private int booksBorrowed;

I found that if I want to access them in my second class "Student" I have to add a get method in my "LibraryCard" class:

    public int getlimit()
    {
    return this.limit;
    }

    public int getbooksBorrowed()
    {
    return this.booksBorrowed;
    }

After accessing these 2 variables I need to use them in an if statement in my "Student" class: Which i have implemented this way

    public boolean finishedStudies()
    {
    if ( (this.booksBorrowed = 0) && (this.booksBorrowed >= this.limit)) {
        return true;
    }

    else
       return false;
    }

When i try to compile it BlueJ says it cannot find variable booksBorrowed and limit

I am very new to Java and Programming in general, help would be greatly appreciated.


Solution

  • You have the create an instance of your LibraryCard class inside your Student class and then you can access the two variables by invoking the getters on that instance:

    LibraryCard card = new LibraryCard();
    int limit = card.getlimit();
    int booksBorrowed = card.getbooksBorrowed();