[英]Use an object in another class
I want to use the object person in the Librarian_Interface class, but this call the method login() in a loop.我想在 Librarian_Interface class 中使用 object 人,但这会在循环中调用方法 login()。 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.
我认为 java 实例有一些我不明白的地方,我试图用构造函数或方法来找人,但徒劳无功。 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(); ...
All you have to do is pass the person
object to the Librarian_Interface
constructor.您所要做的就是将
person
object 传递给Librarian_Interface
构造函数。 then you can call methods getAge
on it, etc.然后你可以在它上面调用方法
getAge
等等。
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.顺便说一句,Java 中的约定是对 class 名称使用大写的驼峰式大小写,不带下划线。 So it would be better to name the class
LibrarianInterface
.所以最好命名为 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
.此外,如果它实际上是
class
而不是interface
,则称它为LibrarianInterface
可能不是最好的主意。
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.由于
Librarian
有一个公共的run
方法,最好让它实现Runnable
以便 class 的用户了解它的使用方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.