我正在上一门Java课程,所以我尝试使代码含糊一些,以便我可以学习但不能作弊。该作业将采用上周的程序并扩展功能。基本上,我编写了一个程序,在其中使用两种情况下的switch(不确定这是最佳选择,但这是我所做的),并且我想添加更多用户选项。因此,它当前允许输入“ w”,“ x”,但是我想通过将类A扩展为类B来添加“ y”和“ z”作为选项。
类A中有一个默认情况,该情况基本上输出“仅输入'w'和'x'”。问题在于,即使使用新的B类对其进行了扩展,它也只能阻止'w'和'x'。
我知道我需要B类重写它,以便它允许w,x,y和z,然后在输入除这四个选项以外的任何内容时触发默认值。无论哪种方式,请帮助!
下面是A类(我摆脱了一些代码,但是所有变量,用户输入和扫描程序都起作用。在这种情况下,我遇到了问题):
import java.util.Scanner;
public class A {
public A()
{
// define and implement variables
// call scanner into existance to read inputs from the user
// Ask for user input (abbreviated section) and store in variables
oper = myManager.next(".").charAt(0);
switch(oper)
{
// case w call to firstMethod method
case 'w':
DoSomething = firstMethod(num1,num2);
System.out.println(" The result is "+FirstAns);
break;
// case w call to secondMethod method
case 'x':
DoSomethingElse = secondMethod(num1,num2);
System.out.println(" The result is "+SecondAns);
break;
default:
System.out.println(" Please Enter 'w' or 'x' only.");
}
/* note, this portion I got rid of some work, it's normally
math related but modified here just to return characters for
this post since I think it's irrelevant to my question (and I
don't want to cheat) */
static char firstMethod(char a)
{
return a;
}
static char secondMethod(char a)
{
return a;
}
}
}
下面是扩展A的B类,我不能说服允许更多的情况。请注意,编译后,我正在执行B,但是它仍然只允许来自A的情况。
import java.util.Scanner;
public class B extends A {
public B()
{
// define and implement variables
// call scanner into existance to read inputs from the user
// Ask for user input (abbreviated section) and store in variables
oper = myManager.next(".").charAt(0);
switch(oper)
{
// case w call to firstMethod method
case 'w':
DoSomething = firstMethod(num1,num2);
System.out.println(" The result is "+FirstAns);
break;
// case w call to secondMethod method
case 'x':
DoSomethingElse = secondMethod(num1,num2);
System.out.println(" The result is "+SecondAns);
break;
case 'y':
DoSomethingMore = thirdMethod(num1,num2);
System.out.println(" The result is "+ThirdAns);
break;
// case w call to firstMethod method
case 'z':
DoSomethingLast = fourthMethod(num1,num2);
System.out.println(" The result is "+FourthAns);
break;
default:
System.out.println(" Please Enter 'w', 'x', 'y', or 'z' only.");
}
}
// again, simplified this portion
static char thirdMethod(char a)
{
return a;
}
static char fourthMethod(char a)
{
return a;
}
public static void main(String[] args) {
B b = new B();
}
}
然后,我更新测试程序以导入B类(而不是导入A的旧程序,因为B应该扩展A)。但是它仍然仅显示来自A的案例。我知道这是程序如何加载案例的操作顺序,只是不确定如何解决。
父类的默认构造函数始终始终由子类的默认构造函数首先调用。
在您的示例中,使用默认构造函数创建类B时,将调用类A构造函数。
一种解决方案是将逻辑移到两个类中具有相同签名的方法中,然后在超类的构造函数中调用该方法。
像这样:
class A {
public A() {
logic();
}
private void logic() {
// Your switch of A
}
}
class B extends A {
public B() {
super();
}
private void logic() {
// Your switch of B
}
}
动态绑定是此解决方案背后的OO原则。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句