1

I come from C++, and actually I haven't really used class inheritance at college yet, so I'm learning by myself. I'll put my doubt in the form of an example:

Let's say I have a class called Entity. This entity class holds two integers representing some X and Y coordinates (this is not relevant, it could be any other field). Then I have my class Player, extending Entity. As it might seem usual, I want Player to use as well the x and y fields, and some code in the Entity class refers to those fields as well.

Now comes my doubt. Are x and y public, private or protected? I feel like they should be protected, as public is not an option (Other classes should'nt be accessing it) and private doesn't allow me to use the x and y fields from the extended (Player) class. But I read elsewhere that class fields should never be protected, only methods.

Other sollutions to this other than setting the variable to protected that come into mind would be using getters and setters from the super class (which in my opinion is not only a bad practice but completely redundant and unnecesary), or re-declaring those attributes in the new class, which let's me thinking if I'm getting any reward from inheritance if I'll have to type all the field declarations twice. I actually don't even know if this last thing might work as I don't know Java that well to know how it handles this visibility issues.

Any help on the topic would be much appreciated.

Thank you.

4

4 回答 4

4

[Using getters and setters]... which in my opinion is not only a bad practice but completely redundant and unnecessary

Actually no, this is often considered the best approach. There are a variety of reasons to favor it, ranging from maintainability to security. You would make the fields private, and declare methods in the base class to both access and alter them.

于 2013-07-24T20:21:46.670 回答
2

if you want variables to be accessible through subclass, you need to make them protected. but still those will be accessible from other classes but in same package. however those will be protected from classes outside of the package, except those who inherit your class where the variables are defined.

And yes, instead of making variables themselves as private, you should define setters to access them. It is not at all bad practice, in fact its best practice in all object oriented programming.

于 2013-07-24T20:20:49.973 回答
1

这实际上取决于实体类的目的。如果它只是 x 和 y 的持有者——因为你的许多类都会使用它们,那么让它们受到保护就很好了。

如果有任何逻辑绑定到这些坐标 - 特别是验证,更改时的某些事件。然后您需要使用 getter/setter 将这个逻辑封装在 Entity 类中。

没有什么是一成不变的,你总是可以重新设计它——只要其他开发人员不依赖它。如果你有其他依赖于你的代码——你必须设计得更安全。但不要过度设计。

于 2013-07-24T20:39:08.220 回答
0

在这种情况下你不能不使用访问说明符吗?使用protected(除非我弄错了)允许所有子类,包括来自不同包的子类,都可以访问。在大多数(但不是全部)情况下,您只是为自己编写一个小程序,如果您希望子类可以访问超类的变量,则可能没有访问说明符。

这张图片应该为您提供有关所有不同访问说明符的信息。“包”列指的是同一包中的子类,“子类”列指的是与包无关的子类。 在此处输入图像描述

于 2013-07-24T20:35:58.910 回答