如何调用一个包中的基类的构造函数,该包中的基类的构造函数具有 protected 访问修饰符,不受另一包中的派生类的访问修饰符的影响? 像这样: 包含派生类的包:
package MainPack;
import mypack.Checker;
import java.util.Scanner;
public class Start
{
public static void main(String[] args)
{
BeginCheck bc=new BeginCheck();
}
}
class BeginCheck extends Checker
{
BeginCheck()
{
System.out.print("Enter a String to Check: ");
super(new Scanner(System.in).nextLine()); //I want to call it like this
}
}
包含基类的包:
package mypack;
public class Checker
{
String s;
protected Checker()
{
}
protected Checker(String s)
{
s=this.s;
}
}
最佳答案
BeginCheck()
{
System.out.print("Enter a String to Check: ");
super(new Scanner(System.in).nextLine()); //I want to call it like this
}
对 super 构造函数的调用必须是每个构造函数中的第一行。除非您调用默认构造函数,否则您可以省略该调用,编译器将推断它。
BeginCheck() {
super( new Scanner( System.in ).nextLine() );
}
不过,您确实不应该在构造函数中执行用户 IO。它应该保留用于仅将对象初始化为可用状态。
关于java - 使用 super 关键字从不同包调用基类的 protected 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25322952/