【问题标题】:Calling child method, when cast to parent type in java调用子方法,当在java中转换为父类型时
【发布时间】:2011-11-21 05:04:47
【问题描述】:

我在尝试完成一些课程作业时遇到问题,我们将不胜感激!

我有 3 种类型的帐户,它们扩展了抽象类型“帐户”。[CurrentAccount、StaffAccount 和 MortgageAccount]。

我正在尝试从文件中读取一些数据并创建帐户对象以及用户对象以添加到程序中存储的哈希图中。

当我创建帐户对象时,我使用帐户类型的临时变量并根据读入的数据定义其子类型。

例如:

Account temp=null;

if(data[i].equalsIgnoreCase("mortgage"){
    temp= new MortgageAccount;
}

问题是当我尝试调用属于 MortgageAccount 类型的方法时..

我是否需要每种类型的临时变量 StaffAccount MortgageAccount 和 CurrentAccount 并相应地使用它们以使用它们的方法?

提前致谢!

【问题讨论】:

  • 是的,您需要为每种类型设置临时变量。不能通过父引用调用子方法。或者你必须将对象转换为它的子类型,然后你可以调用它的方法。

标签: java polymorphism class-hierarchy


【解决方案1】:

如果您的所有帐户对象都具有相同的接口,这意味着它们声明了相同的方法并且它们仅在实现方式上有所不同,那么您不需要为每种类型使用一个变量。

但是,如果要调用特定于子类型的方法,则需要该类型的变量,或者需要转换引用才能调用该方法。

class A{
    public void sayHi(){ "Hi from A"; }
}


class B extends A{
    public void sayHi(){ "Hi from B"; 
    public void sayGoodBye(){ "Bye from B"; }
}


main(){
  A a = new B();

  //Works because the sayHi() method is declared in A and overridden in B. In this case
  //the B version will execute, but it can be called even if the variable is declared to
  //be type 'A' because sayHi() is part of type A's API and all subTypes will have
  //that method
  a.sayHi(); 

  //Compile error because 'a' is declared to be of type 'A' which doesn't have the
  //sayGoodBye method as part of its API
  a.sayGoodBye(); 

  // Works as long as the object pointed to by the a variable is an instanceof B. This is
  // because the cast explicitly tells the compiler it is a 'B' instance
  ((B)a).sayGoodBye();

}

【讨论】:

    【解决方案2】:

    这取决于。如果父类AccountMortgageAccount 中覆盖了一个方法,那么当您调用该方法时,您将获得MortgageAccount 版本。如果方法只存在于MortgageAccount,则需要强制转换变量来调用方法。

    【讨论】:

      【解决方案3】:

      你只需要一个MortgageAccount 类型的对象来调用它的方法。您的对象temp 的类型为MortgageAccount,因此您可以在该对象上调用MortageAccountAccount 方法。不需要强制转换。

      【讨论】:

      • 这是 Eclipse/API 在没有错误的情况下显示错误的情况吗?我无法编译 atm 来测试它是否可以在不强制转换的情况下调用孩子的方法。
      【解决方案4】:

      这是Dynamic method dispatch的概念

      如果您使用基类的引用变量并创建派生类的对象,那么您只能访问在基类中定义或至少声明的方法,并且您在派生类中覆盖它们。

      要调用派生类的对象,你需要派生类的引用变量。

      【讨论】:

        猜你喜欢
        • 2015-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-08
        • 1970-01-01
        • 2017-07-22
        相关资源
        最近更新 更多