我想知道具有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();
}
}
结果:构造函数Saving(int)不可见。
答案 0 :(得分:0)
重点是“保护”修饰符,使您可以访问子类或同一包中的方法。在您的方案中,您既不能访问同一包中的Saving(int num)构造函数,也不能从子类中访问它。
尽管在这种情况下您试图实例化Save到其子类的方法中,实际上实际上是从此类的外部访问受保护的方法/构造函数的尝试。我将尝试修改您的示例以向您显示差异。
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方法本身的错误操作,导致代码无法编译。