Java: Inheritance, Exeptions and super keyword

时间:2018-03-25 18:57:16

标签: java arrays inheritance exception

I have a class X that saves ints in an array:

public class X{
 public int[]        a;
 public boolean[]    allocated;

 //constructor
 public X(int len){
  this.a = new a[len];
  this.a = new allocated[len];
 }


public void save(int tosave) throws ArrayStoreException{
  int pos = 0;

  for(int i=0; i<allocated.length; i++){
    if(allocated[i] == true){
      pos++;
    }
  }

  if(pos == allocated.length){
    throw new ArrayStoreExeption("no free space left");
  }

  a[pos] = tosave;
  allocated[pos] = true;
 }
}

And the class Y with save2 that I still need to implement...

public class Y extends X{

  public void save2(int tosave){

     // to be implemented
  }

}

For save2 I want it to do the same as save with the exception, that if there is no more free space left or the ArrayStoreException occurs then I want the array to be doubled the size and then the parameter inserted to the array.

So if I do:

try{
  super.save(tosave);   // If no exception is thrown, does it save 'tosave'?

}catch(ArrayStoreExeption e){
  System.out.println("noe free sapce left");
}

My first question is: if the try block does not trigger an exeption, will the code after catch block execute? I don't know where to put the piece of code savely which doubles the array size if there is no more space left or the exeption is thrown.

Can someone help?

EDIT: Can I place the code, that double the array inside the catch block?

2 个答案:

答案 0 :(得分:1)

  1. the code you have posted has a number of syntax errors. I suggest you get those fixed and repost if this answer doesn't satisfy you.

  2. yes you can implement your code to expand the array inside the catch block of the subclass. It will need to call the superclass's save method

  3. your subclass should probably override the save method rather than create a new save2 method

  4. using a boolean array doesn't make a lot of sense. Given you are not leaving any gaps wouldn't it be easier just to keep a single index of the first unallocated spot?

  5. wherever possible keep your member variables private or protected. In this case if the subclass is going to expand the array then it will likely need to be protected. Better would be to make it private and have a protected method in the superclass to expand it.

  6. Arrays.copyOf will do the expansion for you

So putting all that together:

class Fixed {
    private int size;
    private int[] store;
    private int index = 0;

    public Fixed(int size) {
        this.size = size;
        store = new int[size];
    }

    public void save(int value) throws ArrayStoreException {
        if (index == size)
            throw new ArrayStoreException();
        store[index++] = value;
    }

    protected void expand() {
        size *= 2;
        store = Arrays.copyOf(store, size);
    }
}

class Expandable extends Fixed {
    public void save(int value) {
        try {
            super.save(value);
        } catch (ArrayStoreException x) {
            expand();
            save(value);
        }
    }
}

If you prefer to avoid the recursion then you could use:

public void save(int value) {
    try {
        super.save(value);
    } catch (ArrayStoreException x) {
        expand();
        try {
            super.save(value);
        } catch (ArrayStoreException x) {
            throw new IllegalStateException("Cannot save after expansion");
        }
    }
}

答案 1 :(得分:0)

You can put the code in finally block. Regardless there is an exception or not, finally block do execute. (Exception : if called System.exit(0); in the try block.)

Conceptually, let's begin with

Try Block - You put the code here where you think there may be an ArrayStoreException.

Catch Block - This Block runs only if there is any exception thrown from try block. You put the code, how it should handle. As per requirement, you can throw a message to console telling about the details of error, as in your case ArrayStoreException message and can prompt the user that you are going to double the capacity of ArrayList and can hence write the code for increasing the size of ArrayList

Finally Block - This block runs regardless of any exception is thrown or not. You can write the code for increasing the size of ArrayList here also. But, it will run even if there is no ArrayStoreException and the ArrayList has the capacity.

Note : If there is an exception thrown by the code, and is not handled or declared, so the code will stop running and no further code will run. But, if there is a proper handling of errors, the rest of the code runs.

For your case, I will suggest definitely to leverage the use of try-catch-finally block and put the code for doubling the size in catch block.