简体   繁体   English

Java:继承,Exeptions和超级关键字

[英]Java: Inheritance, Exeptions and super keyword

I have a class X that saves ints in an array: 我有一个将ints保存在数组中的类X

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... 还有我需要实现的带有save2的类Y ...

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. 对于save2我希望它执行与save相同的操作,但是如果没有更多的可用空间,或者发生ArrayStoreException,那么我希望将数组的大小加倍,然后将参数插入数组。

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? 我的第一个问题是:如果try块未触发异常, catch块之后的代码是否会执行? 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? 编辑:我可以放置代码,在catch块内将数组加倍吗?

  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. 是的,您可以实现代码以在子类的catch块内扩展数组。 It will need to call the superclass's save method 它将需要调用超类的save方法

  3. your subclass should probably override the save method rather than create a new save2 method 您的子类可能应该覆盖save方法,而不是创建一个新的save2方法

  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 Arrays.copyOf将为您进行扩展

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");
        }
    }
}

You can put the code in finally block. 您可以将代码放在finally块中。 Regardless there is an exception or not, finally block do execute. 不管是否有异常,finally块都要执行。 (Exception : if called System.exit(0); in the try block.) (异常:如果在try块中调用System.exit(0);。)

Conceptually, let's begin with 从概念上讲,让我们开始

Try Block - You put the code here where you think there may be an ArrayStoreException. 尝试块 -将代码放在您认为可能存在ArrayStoreException的位置。

Catch Block - This Block runs only if there is any exception thrown from try block. 捕获块 -仅当try块引发任何异常时,此块才运行。 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 根据要求,您可以向控制台抛出一条消息,告知错误的详细信息,例如ArrayStoreException消息,并且可以提示用户您将要使ArrayList的容量增加一倍,因此可以编写代码来增加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. 您也可以在此处编写用于增加ArrayList大小的代码。 But, it will run even if there is no ArrayStoreException and the ArrayList has the capacity. 但是,即使没有ArrayStoreException并且ArrayList具有容量,它也将运行。

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. 对于您的情况,我建议绝对使用try-catch-finally块,并将代码加倍到catch块中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM