Search code examples
javasubclassabstractsuperclass

Add variable from subclass to superclass over constructor


I have an abstract class A where I have lets say 3 variables, String username, String password, char sex. In this class I have a constructor to create an Object of that class with all these variables.

I have another two classes B and C that extend the class A, and each of them adds one of their variables to the Object Person. I.e. class B should add a variable isAdmin, the class C should add a variable isUser.

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, I just want to create these variables in their classes separately and if I call the constructor from these classes B or C, that one of the variables is added to the Object User.

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)}
}

Is that even possible? Thanks in advance!


Solution

  • 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
    

    That is what inheritance is for!

    Is that even possible?
    

    Yes it is perfectly valid.

    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
    

    You only need to have isUser instance variable in your class B. As there is no need to have this variable in class A you don't need to have it in the constructor. You can do something like below

    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;}
    }