包含 main 方法的类可以继承另一个类吗?



我想知道具有main方法的类是否可以扩展其他类。当我尝试时,显示错误

构造函数不可见

解决办法是将"受保护"改为"公共"。但是,我知道如果一个类继承自另一个类,它可以使用受保护的方法。在这里,这不起作用。有谁知道这是怎么回事?

package second;
import first.Accumulator;
public class Saving extends Accumulator {
    protected Saving() {
        super()
    }
    protected Saving(int num) {
        super(num);
    }
    protected void addAmount(int amount) {
        add(amount);
    }
    protected void showAmount() {
        show();
    }
}
package third;
import second.Saving;
public class SavingTest extends Saving {
    public static void main(String[] args) {
        Saving saving = new Saving(100);
        saving.addAmount(100);
        saving.showAmount();


    }
}

结果:构造函数保存(int)不可见。

点是"受保护"修饰符允许您访问子类或同一包中的方法。在您的场景中,您既不访问同一包中的 Saving(int num) 构造函数,也不从子类访问它。

尽管在这种情况下,您尝试在其子类的方法中实例化保存,但实际上可以从此类外部访问受保护的方法/构造函数。我将尝试修改您的示例以向您展示差异。

package second;
import first.Accumulator;
public class Saving extends Accumulator {
    public Saving() { // change this one to public to have possibility to instantiate it
        super(); 
    }
    protected Saving(int num) {
        super(num);
    }
    protected void addAmount(int amount) {
        add(amount);
    }
    protected void showAmount() {
        show();
    }
}
package third;
import second.Saving;
public class SavingTest extends Saving {
    // this IS the instance of our superclass
    // but we can't access its protected methods 
    // from THIS instance because it is NOT the same instance
    // either we can't access it from static methods
    private Saving saving1 = new Saving(); 
    public static void main(String[] args) {
        Saving saving = new Saving(100);
        saving.addAmount(100);
        saving.showAmount();
    }
    protected Saving(int num) {
        super(num); // still can access protected constructor of superclass here
    }
    public void nonStaticMethod() {
        saving1.addAmount(100); // can't do this, we try to access protected method from another package and NOT from subclass
        addAmount(100); // can do this! we really access protected method of THIS instance from subclass 
    }
}

因此,底线是继承另一个类包含main方法的类没有任何问题。您实际上已经完成了此操作,但是由于 main 方法本身中的错误操作,您的代码无法编译。

最新更新