0

I have a Java superclass with a private field 'variable' and all its subclasses use 'variable' the same way. Except in every subclass 'variable' gets calculated differently upon initialisation. Where do I best store this field and how do I best initialise it?

This is my code:

public abstract class SuperClass {

    private int variable;

    public abstract String getName();

    public void printVariable() { System.out.println(variable); }

    public int squareVariable() { 
        variable *= variable; 
        return variable;
    }

}
public class SubClass1 extends SuperClass {

    private String name;

    public SubClass1(int param) {
        name = "SubClass1";

        super.variable = param + 1;
        // How do I make this better?
    }

    public String getName() { return name; }

}
public class SubClass2 extends SuperClass {

    private String name;

    public SubClass2(int param) {
        name = "SubClass2";

        super.variable = param / 2;
        // How do I make this better?
    }

    public String getName() { return name; }

}

As you can see, right now I use super.variable, but then I have to make 'variable' protected and that approach doesn't seem optimal to me. What is the right way to do this? Should I define a setter in the superclass? Or can I define a constructor in the superclass which handels this? Or should I store 'variable' in each subclass separately? Or should I keep it like this and make 'variable' protected?

1
  • 1
    Pass param + 1, param / 2 etc to the constructor of the superclass. Commented Apr 28, 2020 at 14:36

1 Answer 1

1

First, the code in the question doesn't compile (The field SuperClass.variable is not visible), so they are bad examples to being with.

Store both variable and name in SuperClass, and initialize them in a constructor.

public abstract class SuperClass {

    private String name;
    private int variable;

    protected SuperClass(String name, int variable) {
        this.name = name;
        this.variable = variable;
    }

    public String getName() { return name; }

    public void printVariable() { System.out.println(variable); }

    public int squareVariable() { 
        variable *= variable; 
        return variable;
    }

}
public class SubClass1 extends SuperClass {

    public SubClass1(int param) {
        super("SubClass1", param + 1);
    }

}
public class SubClass2 extends SuperClass {

    public SubClass2(int param) {
        super("SubClass2", param / 2);
    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.