Java中的对象与扩展 [英] Object vs Extend in Java
问题描述
由于我对Java没有太多的经验,所以我可能是错的,但这是一个问题.
I may be wrong as I have not got too much experience with Java, but here is a question.
我有一个包含许多方法的类(基本上是一个简单的库).
I have a class which contains many methods (basically it is a simple library).
我创建了此类的对象,假设MyLibrary obj = new MyLibrary(parameters);
I create an object of this class let's say MyLibrary obj = new MyLibrary(parameters);
参数设置了库正常运行所需的任何功能.
The parameters set up any necessary functionality for the library to run correctly.
然后我可以呼叫obj.getSomething
/obj.setSomething
/obj.createSomething
等,等等...
Then I can call obj.getSomething
/obj.setSomething
/obj.createSomething
etc etc...
在我的主类中,我真的只需要一个这种库对象.
In my main class I really need only one this kind of library object.
现在...对我来说,不将其用作对象,而是将其作为extends
使用,然后在库内部创建一个像构造函数一样要手动调用的函数,会更有用吗?
Now... Would it be more useful for me not to use it as an object, but put it as extends
and then create a function inside of the library like a constructor which I would call manually?
一个类和MyLibrary之间的关系非常紧密.基本上,我有许多类,它们执行相似的操作,但具有一些不同的高层功能.因此,我分离了所有类中必须必须的方法.
The relation between the one class and MyLibrary is very close. Basically, I have many classes which do similar things but have some different higher layer functionality. So I separated method which must be in all those classes.
似乎与shape
类和triangle
,circle
,square
示例非常相似.因此,MyLibrary
与包含所有基础的shape
相似.
It seems it is very similar to shape
class and triangle
, circle
, square
example. So MyLibrary
is similar to shape
which contains all the foundation.
推荐答案
您所描述的内容与 utility类非常相似,类似于Java的
What you described strongly resembles a utility class, similar to Java's Collections
. The class has only static
methods, and a private constructor to prevent instantiations. This is a well-known idiomatic pattern in Java - you can use it to create your own groups of methods providing related functionality.
您根本不应该扩展或实例化实用程序类.从Java-5开始,您可以静态导入它们,以便可以在不显式引用其类的情况下使用它们的方法.
You should not extend, or even instantiate, utility classes at all. Starting with Java-5, you can statically import them so that you could use their methods without making an explicit reference to their class.
这篇关于Java中的对象与扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!