我可以注释从超类继承的成员? [英] Can I annotate a member inherited from a superclass?

查看:128
本文介绍了我可以注释从超类继承的成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个类,如:

 类Person {
  私人字符串名称;
  ...构造函数,getter方法​​,setter方法​​,平等相待,哈希code,...的toString
}

我可以继承和应用注释名称字段中的子类,例如应用持久性的注释,而无需重新实现类的其他人呢?

  @Entity
Employee类扩展了人{
    @柱(...)
    私人字符串名称;
}


解决方案

没有,你不能。

你所建议的是现场的阴影的 - 你不能覆盖一个字段

字段名称在子类中有没有任何关系与现场名称中的超类,其他比它的股票的名称相同的名字,从而领域区分超类,我们必须把它称为 super.name 中的子类。

这样做通常被认为是一个错误(或反正潜在的错误),和最佳实践是不是暗影领域,因为它是那么容易引用了错误的领域而不自知。

If I have a class such as:

class Person {
  private String name;
  ...constructor, getters, setters, equals, hashcode, tostring...
}

Can I subclass and apply annotations to the name field in the subclass, for example to apply persistence annotations, without re-implementing the rest of the class?

@Entity
class Employee extends Person {
    @Column(...)
    private String name;
}

解决方案

No, you can't.

What you are proposing is field shadowing - you can't override a field.

The field name in the subclass has nothing whatsoever to do with the field name in the super class, other than it shares the same name of "name" and thus to distinguish the field in the super class, one must refer to it as super.name in the subclass.

Doing this is generally considered a "bug" (or a potential bug anyway), and best practices are to not shadow fields, because it is so easy to refer to the wrong field without knowing it.

这篇关于我可以注释从超类继承的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆