0

I want to declare an array in a base class but instantiate it only in subclasses. I need to do stuff like get the length of this array in base class but it's coming up as null. I only need to instantiate subclasses. Can I do this someway? Thanks for any help in advance...

public class A {  

protected int[] array;

    public void someMethod() {
        variable = array.length;
    }
}  

public class B extends A {  
    public void doSomething() {  
        array = new int[] { 1,2,3 };  
    }  
} 
1
  • Your array would be coming up as null until B.doSomething is called. After that, it would no longer be null. Commented Sep 14, 2013 at 10:06

2 Answers 2

2

You can do it this way if A can be declared abstract.

public abstract class A {  

    protected int[] array;

    public void someMethod() {
        int[] array = getArray();
        variable = array.length;
    }

    protected abstract int[] getArray();
}  

public class B extends A {  
    public int[] getArray() {
        if(array == null){
            array = new int[] { 1,2,3 };  
        }
        return array;
    }  
}

Nevertheless you should not use A as a variable holder that gets initialized from some subclass. This might confuse developers since they might not know which method to call that initializes the array, because they might not know all subclasses.

A better approach would be to just use the abstract method.

public abstract class A {  


    public void someMethod() {
        int[] array = getArray();
        variable = array.length;
    }

    protected abstract int[] getArray();
}  

public class B extends A {  

       private int[] array;

    public int[] getArray() {
        if(array == null){
            array = new int[] { 1,2,3 };  
        }
        return array;
    }  
}
Sign up to request clarification or add additional context in comments.

1 Comment

I'd tried this approach but couldn't get it to work. The reason was I had hard coded array instantiation as a property in subclass rather than forming it in actual method like you are doing above. I like your thought about subclasses not knowing how to instantiate something? That's got me thinking about abstract properties but no doubt that is discussed elsewhere. Thanks for your prompt help.
0

Proper encapsulation should work in your case:

public class A {

  private final int[] array;

  public A(final int[] array) {
    this.array = array;
  }

  public int[] getArray() {
    return this.array;
  }

  // other methods...
}

public class B extends A {

  public B() {

    // instantiate the array
    super(new int[] {});
  }
}

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.