Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

Java final abstract class

I have a quite simple question:

I want to have a Java Class, which provides one public static method, which does something. This is just for encapsulating purposes (to have everything important within one separate class)...

This class should neither be instantiated, nor being extended. That made me write:

final abstract class MyClass {
   static void myMethod() {
      ...
   }
   ... // More private methods and fields...
}

(though I knew, it is forbidden).

I also know, that I can make this class solely final and override the standard constructor while making it private.

But this seems to me more like a "Workaround" and SHOULD more likely be done by final abstract class...

And I hate workarounds. So just for my own interest: Is there another, better way?

question from:https://stackoverflow.com/questions/9618583/java-final-abstract-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't get much simpler than using an enum with no instances.

public enum MyLib {;

   public static void myHelperMethod() { }
}

This class is final, with explicitly no instances and a private constructor.

This is detected by the compiler rather than as a runtime error. (unlike throwing an exception)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...