我有一个称为PageObject的超类,然后有两个称为AlphaPage和BetaPage的子类继承PageObject。 函数“selectPage()”将返回这些页面中的一个,但只有在运行时才能知道要返回的特定页面。
函数的返回对象应该是什么,那么这将避免必须将其中一个子类转换为函数调用的返回值?
I have a super class called PageObject, and then two subclasses called AlphaPage and BetaPage that inherit the PageObject. A function "selectPage()" will return one of these pages, but the specific page to return will only be known at runtime.
What should the function's return object be, then, that will avoid having to cast one of the subclasses to the function call's return val?
最满意答案
如果调用者想要特定的类型,则只需在执行时知道该信息即可。 基本上你应该返回PageObject 。
当然,如果调用者不需要特定于AlphaPage或BetaPage任何东西 - 如果他们只能使用在PageObject声明的方法(可能是抽象的),那么就不需要投射。 这将是理想的使用多态性来处理差异。 这真的取决于调用者需要做什么。
The caller will have to cast if they want the specific type, given that the information is only known at execution time. You should return PageObject, basically.
Of course, if the caller doesn't need anything specific to AlphaPage or BetaPage - if they can just use methods (possibly abstract) declared on PageObject, then there'll be no need to cast. That would be the ideal - use polymorphism to handle the differences. It really depends on what the caller needs to do though.
如果它的返回值是仅在运行时已知的两个可能对象之一,那么我的java函数应该返回什么对象?(What object should my java function return if its return value is one of two possible objects known only at runtime?)我有一个称为PageObject的超类,然后有两个称为AlphaPage和BetaPage的子类继承PageObject。 函数“selectPage()”将返回这些页面中的一个,但只有在运行时才能知道要返回的特定页面。
函数的返回对象应该是什么,那么这将避免必须将其中一个子类转换为函数调用的返回值?
I have a super class called PageObject, and then two subclasses called AlphaPage and BetaPage that inherit the PageObject. A function "selectPage()" will return one of these pages, but the specific page to return will only be known at runtime.
What should the function's return object be, then, that will avoid having to cast one of the subclasses to the function call's return val?
最满意答案
如果调用者想要特定的类型,则只需在执行时知道该信息即可。 基本上你应该返回PageObject 。
当然,如果调用者不需要特定于AlphaPage或BetaPage任何东西 - 如果他们只能使用在PageObject声明的方法(可能是抽象的),那么就不需要投射。 这将是理想的使用多态性来处理差异。 这真的取决于调用者需要做什么。
The caller will have to cast if they want the specific type, given that the information is only known at execution time. You should return PageObject, basically.
Of course, if the caller doesn't need anything specific to AlphaPage or BetaPage - if they can just use methods (possibly abstract) declared on PageObject, then there'll be no need to cast. That would be the ideal - use polymorphism to handle the differences. It really depends on what the caller needs to do though.
发布评论