0

I have an abstract class and in that abstract class I have an array and I want every class that extends it to have the array 2 ints long no matter what. I know you can define array size in methods but thats all you can do it in. Here's some code

public abstract class entity{

int pos[]

// want this variable to be two ints long no matter what extends it
}

Is this possible?

4 Answers 4

4

You could instantiate the array in the superclass and limit the access to it with methods. That way no subclass can change the size of the array.

private int[] pos = new int[2];

protected void setPos(int index, int value) {
    pos[index] = value;
}

protected int getPos(int index) {
    return pos[index];
}
Sign up to request clarification or add additional context in comments.

Comments

2

Why do you need the extending classes to initialize it? You can initialize it to int[2] in the super class itself.

BTW your class entity should be called Entity. pos can be final or private or both.

Comments

1
protected final int[] pos = new int[2];

Declaring it protected ensures that all types that are derived from it will have access to it.

Declaring it final ensures that no derived type will change what the reference points to.

Comments

0

try this

int[] pos = new int[2];

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.