【发布时间】:2020-10-23 11:40:32
【问题描述】:
我目前正在学习 OOP java 课程。在下面的代码中,我在运行时实现多态性以及继承。我正在创建一个名为“平衡”的常量。 该程序的目标是创建一个名为 Account 的类,并使用 SBaccount 和 current 两种类型的类扩展该类。
与Account 共享的共同属性是name、number 和amount。到目前为止,我有一个工作代码,但它还没有完成我想要的。 一旦用户指定了我想要验证用户输入的类型,我希望能够询问用户需要创建的帐户类型。例如,如果用户存入 xx 金额,我还想将该金额添加到余额中然后存储。我想在“提款”方法中,当用户提款时,它应该从余额中取出。
我的代码:
import java.util.Scanner;
abstract class Account{
String number;
String name;
int amount;
static final int balance = 1000;
int bal;
public Account(){
}
int deposit(int i) {
return i;
}
void withdrawal(int i){
}
}
final class sbaccount extends Account {
public sbaccount() {
// TODO Auto-generated constructor stub
}
int deposit (int money){
bal = money + balance;
System.out.println("You have deposited :$"+money );
System.out.println("Your Account balance is now :"+bal);
return bal;
}
void withdrawal(int withdraw){
if (bal <= balance){
System.out.println("Your balance is too low for withdrawal!");
}
else{
amount = bal - withdraw;
System.out.println("You have withdrawn :$"+ withdraw);
System.out.println("Your Account balance is now :"+ amount);
}
}
}
final class current extends Account {
public current() {
}
int deposit ( int money){
bal = money + balance;
System.out.println("You have deposited :$"+money);
System.out.println("Your Account balance is now :"+ bal);
return bal;
}
void withdrawal(int withdraw){
if (bal <= balance){
System.out.println("Your balance is too low for withdrawal!");
}
else{
amount = bal - withdraw;
System.out.println("You have withdrawn :$"+ withdraw);
System.out.println("Your Account balance is now :"+ amount);
}
}
}
public class oopassignment {
public static void main(String[] args) {
String type;
Scanner input = new Scanner (System.in);
System.out.println("What type of account do you want to create? :");
type=input.nextLine();
Account sb;
sb = new sbaccount();
sb.deposit(500);
sb.withdrawal(100);
sb = new current();
sb.deposit(500000);
sb.withdrawal(1000000);
}
}
【问题讨论】:
-
什么是“聚合”?你的意思是多态性?
-
是的,我的意思是运行时的多态性**,对此感到抱歉
-
仅供参考,您应该正确格式化您上传的代码。此外,这并不是一个真正的 OOP 问题,因此您应该调整标签和标题。您似乎想要的是一种存储用户输入的方法。
-
感谢您的提示,我是 Stack 的新手,所以我目前只是掌握它的窍门。
标签: java oop object inheritance polymorphism