简体   繁体   English

从父类访问子类变量

[英]accessing subclass variable from parent class

I have a declaration like this 我有这样的声明

TransactionItemDto itemDto = getTransactionItemMessage().getTransactionItemDto();

then I have the following piece of code: 然后我有以下代码:

if (itemDto instanceof ChangeTransactionItemDto) {
            inputItem.setSiteCode(itemDto.getSiteCode()));
            inputItem.setBinLocation(itemDto.getBinLocation()));

        }

Now, I have variable ' department ' which belongs to ChangeTransactionItemDto only. 现在,我有ChangeTransactionItemDto仅属于ChangeTransactionItemDto变量' department '。 But I am not able to do this currently inside the if block above: inputItem.setDepartment(itemDto.getDepartment())); 但我目前无法在上述if块内执行此操作: inputItem.setDepartment(itemDto.getDepartment()));

Thats because itemDto is declared of type TransactionItemDto and not ChangeTransactionItemDto . 那是因为itemDto声明为TransactionItemDto类型,而不是ChangeTransactionItemDto类型。

I can check the value during the debug process if I do itemDto.getDepartment() since internally its of the subclass type. 如果我执行itemDto.getDepartment()则可以在调试过程中检查该值,因为在内部它是子类类型。 but the statement gives error. 但是该语句给出了错误。 How do I set the department belonging to the subclass - ChangeTransactionItemDto on the inputItem ? 如何在ChangeTransactionItemDto上设置属于子类ChangeTransactionItemDtoinputItem

由于已验证itemDto是否属于实例ChangeTransactionItemDto ,因此您始终可以调用inputItem.setDepartment(((ChangeTransactionItemDto)itemDto).getDepartment())

It is a design smell if super class needs access to subclass-specific fields. 如果超类需要访问特定于子类的字段,这是一种设计气味。

One work around is to pull the getter/setter up into the super class with a "do nothing" implementation, then those sub classes that use it override it with a "do something" implementation. 一种解决方法是通过“不执行任何操作”实现将吸气剂/设置器拉入超类,然后使用它的那些子类通过“执行某事”实现将其覆盖。

This way there is no class in the class hierarchy that needs special treatment - they can all be treated the same way. 这样,在类层次结构中就没有需要特殊处理的类-它们可以用相同的方式处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM