简体   繁体   中英

How to change the type of a variable of a super class in a subclass?

I am trying to create a constructor in a subclass, but I want to change one of its "inherited" variables to something more appropriate for the subclass without changing the functionality of the superclass (specifically, I am trying to change the type of the variable from a String to an Object I made in another class). Problem is, I can't directly change or access the variable because it is private in the superclass and there is no setters for this variable.

Is there some other way to effectively override the superclass constructor so I can modify this "inherited" variable without editing the superclass? Or should I not be inheriting from the superclass in this case, even though all the other methods would remain mostly untouched?

Essentially, what I want to do is something like this:

//This should not be changed
public class Super
{
    private SomeArrayObject<String> o;
    private String a;
    private SomeObject b;

    public Super(String a, SomeObject b)
    {
        this.a = a;
        this.b = b;
        o = new SomeArrayObject<String>();
    }

    public void someMethod()
    {
        //Does something
    }
}

public class Sub
{
    private SomeArrayObject<ObjectFromOtherClass> o; //Notice the diff?

    public Sub(String a, SomeObject b)
    {
        super(a, b);
        o = new SomeArrayObject<ObjectFromAnotherClass> o;
    }
}

As a quick note, there is no "default constructor" in the superclass, so I can't just use super() and fill in the variables as needed.

I can see your problem. You can't modified it because is private right? and it's ok to be private variable, but in this such of cases, you can change the visibility of the variable to protected , so the subclass can see it and modify it.

Edit:

Seeing the new info, you have to do a few little changes more, add a generic, and makke the variable protected, an create a new generic class:

public class SuperClassGen<A>  {
    protected ArrayList<A> o;
    private String a;
    private int b;

    public SuperClassGen(String a, int b) {
        this.a = a;
        this.b = b;
        this.o = new ArrayList<A>();
    }
}

public class SuperClass extends SuperClassGen<String> {
    public SuperClass(String a, int b) {
        super(a, b);
    }
}

public class SubClass extends SuperClassGen<ObjectFromOtherClass> {
    public SubClass(String a, int b) {
        super(a, b);
    }
}

That will allow change the type from the subclass in the constructor, without

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM