【问题标题】:JDBC dao and inheritanceJDBC dao 和继承
【发布时间】:2018-01-07 10:57:47
【问题描述】:

假设我的模型中有 2 个类:

public class Account {
  int capital;
  int numero
  }

public class SavingAccount extends Account{
  double rate;  
}

因此,当我必须使用 JDBC 在数据库中保存或检索帐户时,它可以工作,但对于绑定,大写和数字是可以的,但对于速率,我需要检查类型并进行转换:

if(account.getType() ==  AccountType.SAVINGACCOUNT) {
((SavingAccount)Account).setRate(result.getDouble("rate"));
}

除此之外还有其他方法吗?或者有两种不同的方法?

【问题讨论】:

    标签: java inheritance jdbc dao


    【解决方案1】:

    最后一个也是刚刚实现的类是SavingAccount。 SavingAccount 包含rate's getter and setter 方法。因此,无论何时使用getRate(),都应将Account 类型转换为SavingAccount,因为在SavingAccount 的堆空间中,您有getRate() 方法。

    因为最终实现是通过SavingAccount,您还通过类型检查AccountType.SAVINGACCOUNT 提供正确的数据库事务。

    当您通过Account 实例执行您的程序时,它会为您提供多态能力。这就是为什么它很重要。

    因此,在您的场景中,我认为不存在任何其他解决方案。你做得很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      • 1970-01-01
      • 2019-03-14
      • 1970-01-01
      相关资源
      最近更新 更多