我的应用程序中有几种不同类型的用户(不同类别)
User1
User2
等等...
我想要一个抽象类“User”,它为所有类型的用户加入相同的方法
例如:getId()、getAge()....
我真的不知道这是如何工作的,但我想做的是:
User.setType(2); //a kind a constructor
User.getId()... //etc .. the getId() method of the Users2 class
无需实例化抽象类User
我怎样才能做到这一点? 我遇到的问题是抽象类不能有静态方法...并且 User 必须是静态的或 Singleton 我不知道什么是最好的。
谁能给我一些建议吗?
谢谢
最佳答案
public abstract class User {
private int age;
private int id;
public int getAge() { return age; }
public int getId() { return id; }
}
public class User1 extends User { }
public class User2 extends User { }
User user1 = new User1();
user1.getId();
User user2 = new User2();
user2.getId();
Without having to instantiate the abstract class User
抽象类无法实例化。
User must be static or a Singleton I don't know what is the best.
尽管抽象类可以有静态方法,但这不太有意义(特别是当您需要一个抽象User
和多个特定类型的User
时)。
关于Java 抽象类建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8814277/