0

我有一个抽象类 A,我可以说 3 个变量,字符串用户名,字符串密码,字符性别。在这个类中,我有一个构造函数来创建该类的所有这些变量的对象。

我还有另外两个扩展类 A 的类 B 和 C,它们每个都将它们的一个变量添加到 Object Person。即B类应该添加一个变量isAdmin,C类应该添加一个变量isUser。

我尝试使用构造函数来实现它,但我不想将 B 和 C 类中的任何变量添加到 A,我只想在它们的类中分别创建这些变量,如果我从这些类中调用构造函数B 或 C,将变量之一添加到对象用户。

public class abstract class A {
private String name;
private String password;
private char sex;
public A(String name, String password, char sex){
this.name = name; this.password = password; this.sex = sex;}
}

public class B extends A {
public int isUser = 1;
public B(String username, String password, char sex){
super(username, password, sex)}
}

这甚至可能吗?提前致谢!

4

2 回答 2

1
but I don't want to add any of the variables from classes B and C to A, I just want
to create these variables in their classes separately

这就是继承的意义!

Is that even possible?

是的,这是完全有效的。

I've tried it, but if I put the int isUser in the constructor of the class B I will get
an error, because in the superclass constructor I have 3 variables, and in the class B
constructor I have 4 of them. That is the problem

你只需要在你的 B 类中有 isUser 实例变量。因为在 A 类中不需要有这个变量,你不需要在构造函数中有它。您可以执行以下操作

public class B extends A {
public int isUser = 1;
public B(String username, String password, char sex,int isUser){
super(username, password, sex);
this.isUser = isUser;}
}
于 2013-10-16T19:39:30.780 回答
0

您必须在 A 类中创建空构造函数:

protected A(){}

然后你可以在你的 B 和 C 类中调用这个:

super()

如果不存在构造函数,则在创建新对象时,会自动创建空构造函数。但是,如果存在某些构造函数,则不会自动创建构造函数,因此如果您想要空构造函数,则必须手动添加。

I've tried to make it with constructors, but I don't want to add any of the variables from classes B and C to A

我不确定,如果您正确理解继承。如果您有 B 扩展 A,这意味着当您创建实例 B 时,它具有所有具有类 A 的方法和属性。但是实例 B 将是实例 B,将没有实例 A。它将是实例 B两者的属性 - A 类和 B 类。

于 2013-10-16T19:41:56.713 回答