java中如何将子类的输入提供给父类?
前任
class A () {
class A(int a, int b) {
}
}
class B extends A {
int m;
int n;
class B()
{
getInput(); // i wanna invoke this method first before calling super(). But it does not allow in Java. How to work around this ?
super(m,n);
}
public void getInput() {
Scanner scanner = new Scanner(System.in);
m = scanner.nextInt();
n = scanner.nextInt();
}
public static void main () {
B b = new B();
}
}
Ex
class A () {
class A(int a, int b) {
}
}
class B extends A {
int m;
int n;
class B()
{
getInput(); // i wanna invoke this method first before calling super(). But it does not allow in Java. How to work around this ?
super(m,n);
}
public void getInput() {
Scanner scanner = new Scanner(System.in);
m = scanner.nextInt();
n = scanner.nextInt();
}
public static void main () {
B b = new B();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以强制超类在其构造函数的开头运行一个方法,然后在子类中重写该方法。许多框架都有一个“设置”类型的方法,您可以重写它来完成此类事情。
根据您所编写的类的具体情况,您可能有多个构造函数、用于设置值的公共或受保护方法等。这就是 Java 相当灵活的地方。正如下面的评论所示,这在构造函数中并不是一个很好的实践,但我需要更多的上下文来弄清楚如何完成您所要求的任务。
You can force your super class to run a method at the beginning of its constructor and then override that method in the subclass. Many frameworks have a "setup" type method that you can override to accomplish such things.
Depending on the specifics of the classes you're writing, this is where you might have multiple constructors, public or protected methods for setting values, etc. This is where Java is fairly flexible. As the comments below indicate, this isn't a very good practice in constructors, but I'd need more context to figure out how to accomplish what you're asking.
您可以将多个构造函数链接在一起,就像 jbrookover 以这种方式提到的那样。虽然有点复杂:
You could chain multiple constructors together as jbrookover alluded to in such a manner. Sligtly convoluted though: