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

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

问题描述

如果我有一个类,例如:

If I have a class such as:

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

我是否可以在子类中对 name 字段进行子类化和应用注释,例如应用持久性注释,而无需重新实现类的其余部分?

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;
}

推荐答案

不,你不能.

您提议的是字段 shadowing - 您不能覆盖字段.

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

子类中的字段 name 与超类中的字段 name 没有任何关系,除了它共享相同的名称name",因此为了区分超类中的字段,必须在子类中将其称为super.name.

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天全站免登陆