You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java:继承、异常与super关键字相关技术咨询

Hey there! Let’s start by fixing the bugs in your X class first—those are critical before diving into inheritance and super usage. Then we’ll walk through how to build class Y with the features you need.

Fixing the Buggy X Class

Your original X class has a few syntax and logic issues that need addressing:

  1. Constructor array initialization mistakes: You tried to create arrays using variable names instead of the correct types.
  2. Exception class typo: ArrayStoreExeption is misspelled (missing a 'c').
  3. Flawed save logic: Your current code counts allocated positions and appends to the end, but it skips any empty slots in the middle (if you ever free up space later). We’ll fix this to find the first available slot instead.

Here’s the corrected version of X:

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

    // Constructor
    public X(int len) {
        this.a = new int[len]; // Correctly initialize int array
        this.allocated = new boolean[len]; // Correctly initialize boolean array
    }

    public void save(int tosave) throws ArrayStoreException {
        int pos = -1;
        // Find the first free position in the array
        for (int i = 0; i < allocated.length; i++) {
            if (!allocated[i]) {
                pos = i;
                break;
            }
        }
        if (pos == -1) {
            throw new ArrayStoreException("No free space left"); // Fixed typo
        }
        a[pos] = tosave;
        allocated[pos] = true;
    }
}
Building Class Y with Inheritance, Exceptions, and super

Now let’s tackle class Y, which extends X and includes a save2 method. We’ll cover common use cases for inheritance, exception handling, and the super keyword.

1. Basic Inheritance: Extend X and Add save2 with Exception Handling

In this scenario, Y inherits all fields and methods from X, and save2 wraps the parent’s save method with custom error handling. We use super to call the parent’s constructor and save method:

public class Y extends X {
    // Child class must call parent constructor via super()
    public Y(int len) {
        super(len); // Passes the length to X's constructor
    }

    public void save2(int toSave) {
        try {
            // Use super to invoke X's save method
            super.save(toSave);
            System.out.println("Successfully saved value: " + toSave);
        } catch (ArrayStoreException e) {
            // Custom error handling specific to Y
            System.err.println("Save failed: " + e.getMessage());
            // Optional: Throw a custom exception here if your use case requires it
            // throw new CustomStorageException("Failed to store integer", e);
        }
    }
}

2. Override save and Extend Its Behavior

If you need to modify the save method’s logic but still reuse the parent’s core functionality, override it and use super to call the original method. Here’s an example where we add pre-validation and post-save logging:

public class Y extends X {
    public Y(int len) {
        super(len);
    }

    @Override
    public void save(int toSave) throws ArrayStoreException {
        // Add custom pre-validation before calling parent logic
        if (toSave < 0) {
            throw new IllegalArgumentException("Negative integers are not allowed");
        }
        // Call X's save method to handle the actual storage
        super.save(toSave);
        // Add post-save logic (e.g., logging)
        System.out.println("Saved " + toSave + " at position: " + findLastUsedPosition());
    }

    // Helper method specific to Y
    private int findLastUsedPosition() {
        for (int i = allocated.length - 1; i >= 0; i--) {
            if (allocated[i]) {
                return i;
            }
        }
        return -1;
    }
}

Key Takeaways for Inheritance & super

  • Constructor Chaining: Every child class constructor must invoke a parent constructor (via super()). If you don’t write it explicitly, Java tries to call a no-arg parent constructor—which doesn’t exist in your X class, so you’ll get a compile error.
  • Reusing Parent Logic: Use super.methodName() to call the parent’s version of a method when overriding. This avoids code duplication and keeps your parent class’s core logic intact.
  • Exception Rules: When overriding a method, you can’t throw broader exceptions than the parent method. Since X.save() throws ArrayStoreException, Y.save() can throw the same exception, a subclass of it, or no exception at all.

内容的提问来源于stack exchange,提问作者jdoe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:13:46