In sub class, is it possible to increase the size of array that is declared public in super class. Could you please give me an example.
5 Answers
Arrays are by design fixed length. The length of an array is established when the array is created. After creation, its length is fixed You can't change size dinamically what you can do is reallocate the array (creating a new instance of it maximizing the size (for example *2)) , but if you do that, you have to copy all the content of the previous array. If you want to use a dynamic structure take a look to ArrayList that already handle reallocation of the array etc.

- 14,363
- 4
- 24
- 53
If it's set as protected or public, than yes: A subclass will be able to edit it's parents fields.

- 221
- 2
- 12
-
-
Not all arrays are fixed. Either way, you could easily copy the contents and redefine the length by creating a new array then assigning those copied objects. – Buzzyboy May 12 '14 at 02:28
-
@Buzzyboy Yes, [array lengths are fixed](http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.2). – awksp May 12 '14 at 02:37
-
int[] array = new int[5]; array = new int[6]; ArrayList
ints = new ArrayList – Buzzyboy May 12 '14 at 02:39(); I could go on.
You Should just use a dynamic array:
since all arrays are of fixed-length that once defined cannot be resized.
-
-
-
All a dynamic array is is a fixed-size array that does the swap automatically. – Hot Licks May 12 '14 at 01:45
-
True, but there are a few different ways to create a dynamic array in Java – Nassim May 12 '14 at 01:47
-
I'm pretty sure you can't create a "true" dynamic array in Java, only an array or array-like object (like `ArrayList`) that behaves like a dynamic arrays. Arrays in Java are [defined to have a fixed length](http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.2) – awksp May 12 '14 at 02:38
It's better to use ArrayList than Array with fixed size.
ArrayList<String> ar =new ArrayList<String>();
ar.add("Value");

- 603
- 1
- 5
- 8
In below program SuperArrayClass contain the arr which get be dynamically change in the subArrayClass .in case if you provide the less than the previous size ,in that case it will throw Exception
class SuperArrayClass {
public int arr[];
private int size;
SuperArrayClass(int size) {
this.size = size;
arr = new int[size];
}
public int getSize() {
return size;
}
}
class SubArrayClass extends SuperArrayClass {
SubArrayClass(int size) {
super(size);
}
/**
* @param size
* :provide the new size of the array
* @throws Exception
*/
public void changeSizeTo(int size) throws Exception {
if (getSize()< size) {
int temp[] = new int[size];
for (int i = 0; i < arr.length; i++) {
temp[i] = arr[i];
}
arr = temp;
} else {
throw new Exception("Size provided is less than previous size");
}
}
}

- 1,362
- 16
- 25