Home > Software design >  Use an object in another class
Use an object in another class

Time:01-01

I want to use the object person in the Librarian_Interface class, but this call the method login() in a loop. I think there is something I don't understand with java instance and I tried to get person with a constructor or methode but in vain. Thanks !

public class Login_Interface {
    Person person;

    public Login_Interface() {
        
        db.initConnection();
        person = login(db, in);
        
        if (person != null)
        {
            Librarian_Interface a = new Librarian_Interface();
            a.run();
        }
    }

    public void run() {
    }

    public static Person login(DbConnection db, Scanner sc) {
        Persons.setDbConnection(db);
        Persons persons = Persons.getInstance();

        System.out.print("\nEnter your Phone Number : ");
        String phone = sc.nextLine();

        System.out.print("\nEnter your Password : ");
        String password = sc.nextLine();

        return persons.login(phone, password);
    }

}
public class Librarian_Interface {

public Librarian_Interface() {

// What I want 
// System.out.print(person); or person.getAge(); ...

CodePudding user response:

All you have to do is pass the person object to the Librarian_Interface constructor. then you can call methods getAge on it, etc.

public class Librarian implements Runnable {

    private final Person person;

    public Librarian(Person person) {
        this.person = person;
    }

    @Override
    public void run() {
        int age = person.age();
        // ... whatever else
    }
}

By the way, the convention in Java is to use upper camel case for class names, with no underscores. So it would be better to name the class LibrarianInterface. Also, it's probably not the best idea to call it LibrarianInterface if it is in fact a class and not an interface.

Since Librarian has a public run method, it's a good idea to have it implement Runnable so that users of the class see how it is meant to be used.

  •  Tags:  
  • java
  • Related