如何从基类访问字段的值? [英] How to access values of fields from base class?

查看:84
本文介绍了如何从基类访问字段的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Java的基类访问类的字段.我可以在点网中做到这一点. 参见示例:

I want to access fields of a class from base class in Java. I can do it in dot net. see the example:

public class a{

// here I want to read the value of name or f1 or f2 or every other field values from derived classes
}
public class b extends a{
  public string name;
}
public class c extends a{
  public string f1;
  public string f2;
}

该怎么做?

推荐答案

如果不显式命名子类,则无法读取您的类不拥有的字段.因此,这可以做到如下:

You cannot read the fields your class doesn't own without explicitly naming the subclass. So, this is doable as follows:

((c)this).f1;

但是,这样做会产生不好的代码味道:您现在将a所体现的抽象与其特定的实现/扩展之一联系在一起.您最好重新考虑您的设计.

However, doing this would be a bad code smell: you are now tying an abstraction embodied by a to one of its specific implementations/extensions. You should better rethink your design.

在Java中,必须使用CamelCase命名类,并使用小写字母命名包,否则可能会发生一些非常糟糕的名称解析异常.更不用说任何Java用户完全失去了阅读您的代码的能力.

In Java it is a must that you name your classes using CamelCase and packages using lowercase, otherwise some quite bad name-resolution anomalies can happen. Not to mention any Java user getting totally lost reading your code.

这篇关于如何从基类访问字段的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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