How can I create an utility class? [duplicate] - java

This question already has answers here:
Java: Static Class?
(8 answers)
Closed 8 years ago.
I want to create a class with utility methods, for example
public class Util {
public static void f (int i) {...}
public static int g (int i, int j) {...}
}
Which is the best method to create an utility class?
Should I use a private constructor?
Should I make the utility class for abstract class?
Should I do nothing?

For a completely stateless utility class in Java, I suggest the class be declared public and final, and have a private constructor to prevent instantiation. The final keyword prevents sub-classing and can improve efficiency at runtime.
The class should contain all static methods and should not be declared abstract (as that would imply the class is not concrete and has to be implemented in some way).
The class should be given a name that corresponds to its set of provided utilities (or "Util" if the class is to provide a wide range of uncategorized utilities).
The class should not contain a nested class unless the nested class is to be a utility class as well (though this practice is potentially complex and hurts readability).
Methods in the class should have appropriate names.
Methods only used by the class itself should be private.
The class should not have any non-final/non-static class fields.
The class can also be statically imported by other classes to improve code readability (this depends on the complexity of the project however).
Example:
public final class ExampleUtilities {
// Example Utility method
public static int foo(int i, int j) {
int val;
//Do stuff
return val;
}
// Example Utility method overloaded
public static float foo(float i, float j) {
float val;
//Do stuff
return val;
}
// Example Utility method calling private method
public static long bar(int p) {
return hid(p) * hid(p);
}
// Example private method
private static long hid(int i) {
return i * 2 + 1;
}
}
Perhaps most importantly of all, the documentation for each method should be precise and descriptive. Chances are methods from this class will be used very often and its good to have high quality documentation to complement the code.

According to Joshua Bloch (Effective Java), you should use private constructor which always throws exception. That will finally discourage user to create instance of util class.
Marking class abstract is not recommended because is abstract suggests reader that class is designed for inheritance.

I would make the class final and every method would be static.
So the class cannot be extended and the methods can be called by Classname.methodName. If you add members, be sure that they work thread safe ;)

Making a class abstract sends a message to the readers of your code that you want users of your abstract class to subclass it. However, this is not what you want then to do: a utility class should not be subclassed.
Therefore, adding a private constructor is a better choice here. You should also make the class final to disallow subclassing of your utility class.

Related

How should I implement a singleton class if I need to use method overloading in its construction?

I'm trying to implement something to this effect:
Base class A has a method getFileName()
Two derived classes B and C have overridden implementations of that method, returning file names specific to B and C.
Class A needs to use the services of a singleton class S
The reason I want it to be a singleton is because (a) I want a guarantee that it will only be constructed once and (b) I want eager initialization of that class, which happens at app startup, and not at first use.
Class S needs to do its work work based on the file name (E.g., read in the contents of that file) - which depends on which of A's subclasses is used.
This seems to present an unavoidable conundrum, because:
most implementations of Singleton are static based (pure static class; or ENUM with a static parameter passing)
static classes/methods/blocks cannot call non-static methods...
... and making getFileName() static will make sure that it cannot use inheritance overrides!
How can I implement this design? (I'm open to changing the design if a better pattern is available)
... needs to use the services of a singleton ... which depends on which of A's subclasses is used:
That means the Singleton is not really your problem, it is the acquisition of the correct class based on the type asking!
Your design is too tightly coupled the way you are trying to do it. You need to completely decouple the Service from the Consumers of the service, Singleton is not important in this exercise.
What you need is some form of dependency injection.
This is exactly the type of problem that Guice was created to solve by being able to provide what classes get injected based on another classes type in a binding. That said ...
Most people do not realize that Java has always supported DI via the Constructor. Guice makes this less hard coded, but it is still a dependency that is injected to an instance.
Guice would make this trivial by injecting the correct service based on the class type. But it can be done without any DI framework/library. If using Guice is considered to heavy handed for your case then it can still be done easily.
Below is one way to do it without a framework/library:
public class Solution
{
static class Singleton
{
public static final Singleton INSTANCE;
static { INSTANCE = new Singleton(); }
private Singleton() { /* this is important */ }
public void doWhatever(#Nonnull final B b) { /* whatever */ }
public void doWhatever(#Nonnull final C c) { /* whatever */ }
}
static abstract class A
{
private final Singleton s;
public A(final Singleton s) { this.s = s; }
public abstract String getFilename();
}
static class B extends A
{
public B(final Singleton s) { super(s); }
#Override
public String getFilename() { /* code goes here */ }
}
static class C extends A
{
public C(final Singleton s) { super(s); }
#Override
public String getFilename() { /* code goes here */ }
}
}
The singleton anti-patterns you mention are just that:
The Singleton pattern should by hidden behind a Factory pattern. Your consumers of what needs to have 1 and only 1 should not care if there is 1 and only 1. They should only care that that object conforms to some contract of some interface.
My implementation is a naive Factory to create in static block. Most are create on first use which is not any better.
Using Enum to create Singleton objects is a misuse of the semantics of Enum and an anti-pattern and impossible to properly unit test.
Same with the all static utility class approach, impossible to unit test or replace with a different implementation. A combination of the two is a complete abomination that is impossible to unit test and a complete nightmare to maintain!
How you determine which subclass of A the Singleton works on is easy:
That is what overloading is for as shown in the code above.
Anything else is not doing it right. instanceof fail, reflection bigger fail.
Selecting logic based on Type can be done with overloading methods, or generics or with the appropriate design pattern.
Strategy Pattern would account for that easily and make N number of subclasses manageable and extensible at runtime.
I think you need to decide if S uses A or if A uses S.
If S uses A, then A could be a base class or interface, and S would have a method that accepts instances of A, which are overridden with the correct implementation of getfileName().
If A uses S, then A should be abstract with respect to getFileName() forcing an implementation to be constructed, and it should internally call it's yet-to-be-defined getFileName() passing that as an argument to S.
Singletons are the glue between Object-Oriented solutions and non-Object-Oriented solutions, so you avoid the conundrum by
Having your objects passed to the non-object oriented singleton "utility routine"
Having the resolved parameters passed to the non-object oriented singleton "utility routine"
Example code for the first technique
// this could be abstract class too, as long as getName() is abstract
public interface Nameable
public String getName();
}
public enum Utility {
INSTANCE;
public static deleteByName(Nameable nameable) {
createBackup(nameable.getName());
updateIntentLog(nameable.getName());
removeFile(nameable.getName());
updateAuditLog(nameable.getName());
}
}
or
public abstract class Nameable {
public abstract String getName();
public void delete() {
Utility.INSTANCE.deleteFile(getName());
}
}
public enum Utility {
INSTANCE;
public void deleteFile(String name) {
...
}
}
You can make singleton classes that you initialize manually, i.e. have a static instance variable but also a static initialize() method. The initialize throws if you try to initialize twice. This allows you to choose at run-time which subclass to use and also it makes the initialization order clear.

Why am I able to have a public member in a non-public class?

class MyClass
{
public static final int num=90;
}
Why am I allowed to create a public member in a non-public class?
Is there another way of accessing this member that I do not know of (other than through the class name)?
Since your question was about members, I will address both fields and methods (non-static; Anthony Accioly's answer touches on another good use case, which also includes static fields).
While in many situations this is just an ambiguous consequence of the language's grammar (in particular: public fields in non-public classes, as in your example snippet), there are very good reasons for needing to be able to use public methods in non-public classes.
Expanding on Mik378's answer, consider, e.g., the following (contrived example):
import ...;
class BleebleAscendingComparator implements Comparator<Bleeble> {
#Override public int compare (Bleeble o1, Bleeble o2) { ... }
}
class BleebleDescendingComparator implements Comparator<Bleeble> {
#Override public int compare (Bleeble o1, Bleeble o2) { ... }
}
public class BleebleView {
public enum SortMode { ASC, DESC };
public Comparator<Bleeble> getDisplayOrderComparator (SortMode mode) {
if (mode == SortMode.ASC)
return new BleebleAscendingComparator();
else
return new BleebleDescendingComparator();
}
}
You cannot instantiate one of those Comparator implementations directly outside of that context, but they must override public methods of Comparator, and their functionality is accessible via a Comparator interface.
This same reasoning applies to, e.g., private or protected inner classes. If you were not able to declare methods public, you would have no way of overriding public methods of interfaces that they inherit or classes that they extends.
Practical Examples:
You use this every time you override a public method in an anonymous inner class (e.g. every time you override public void actionPerformed in an anonymous ActionListener).
Consider any non-public class that you would like to store in a HashMap. You would override the public equals() and hashCode() in that non-public class, and the implementation of HashMap can access them regardless of the fact that the class is non-public.
The often overridden public toString() is another common example of a public member of a potentially non-public class.
A more complex example is the use of java.sql.Driver in java.sql.DriverManager (in general, factory-type designs make heavy use of this concept) -- an SQL driver implementation may not make implementation classes public (e.g. the Oracle driver produces non-public Connection objects).
Many more... if you keep an eye out for examples of this, you'll be surprised how common it really is!
Don't forget that classes with default access can be subclassed by public classes in the same package.
package package1;
class MyDefaultClass {
public static final int MY_CONSTANT = 0xCAFEBABE;
}
public class PublicExporter extends MyDefaultClass {
}
Now the public class acts as a bridge, and you are able to consume MyDefaultClass public members from other packages.
package package2;
import package1.PublicExporter;
public class Consumer {
public static void main(String[] args) {
System.out.printf("%x\n", PublicExporter.MY_CONSTANT);
}
}
Consumers can even import static members:
import static package1.PublicExporter.MY_CONSTANT;
public class Consumer {
public static void main(String[] args) {
System.out.printf("%x\n", MY_CONSTANT);
}
}
When a public method belonging to an enclosing class A returns a reference (public supertype reference, like an interface) to its inner class B having default scope, external client (outside A's package) can only call B's methods but can't CREATE themselves fresh instances of B.
If the B's methods weren't public, external client couldn't reach them, and worse: would cause a compilation error since not well implementing its interface.
This modeling could be useful in a certain context, to improve code design.
When you declare a variable public it essentially becomes exactly that ; it's able to be seen throughout your entire program, without any special getters/setters. The class does not necessarily need to be public in order for its members to be public also.
Remember, in Java you can only have 1 public class per compilation unit( .java file), and that public class needs to have the same name as the compilation unit. Other than that, it doesn't "own" ownership of the keyword public.
The fact that you declared num as public and static allows you to say System.out.println(MyClass.num). The public attribute allows you to get the num variable directly. Thus, you do not have to create a method to return num for you. Because it is public, you can also say
MyClass mc = new MyClass();
System.out.println(mc.num);
However, since you also added the static declaration, you should only access it via the class name, i.e MyClass.num
Point to take home: public variables can exist in any type of class, and they allow you to access them without the need for getters and setters. Public classes, however, are not the only classes that can own public variables.

Most concise and efficient way to share common handling code for a per-class object?

I have a series of classes, A,B,C... (several dozen in total) that share common code. There can be many instance of each class A,B,C... . I'm planning to create a superclass, Abstract, that will contain that code instead.
Problem is, the common stuff works on an object that is unique on a per-class (not per-instance) basis. This is currently solved by A,B,C... each having a static field with the corresponding value. Obviously, when I refactor the functionality into Abstract, this needs to be changed into something else.
In practice, it currently looks like this (note that the actual type is not String, this is just for demonstrative purposes) :
public class A implements CommonInterface {
private static final String specificVar = "A";
#Override
public void common() {
specificVar.contains('');
}
}
public class B implements CommonInterface {
private static final String specificVar = "B";
#Override
public void common() {
specificVar.contains('');
}
}
The best idea I've come up with until now is to have a Map<Class<? extends Abstract>,K> (where K is the relevant type) static field in Abstract, and A,B,C... each containing a static initalization block that places the relevant value into the map. However, I'm not convinced this is the best that can be done.
Note that I'm not using any DI framework.
So, what would be the most concise, in terms of code contained in the subclasses, way to refactor the static fields in A,B,C... handled by the common code, without sacrificing field access efficiency?
Perhaps an enum is what you want.
enum MyInstances implements MyInterface {
A {
fields and methods for A
}, B {
fields and methods for B
};
common fields for all MyInstances
common methods for all MyInstances
}
// To lookup an instance
MyInstances mi = MyInstances.valueOf("A");
As you haven't shown any source code, we can't really tell if the use of static fields is a good or a bad design choice.
Considering the use of static fields by the subclasses is indeed a good design choice, the first way of having common code in a superclass to access them is by calling abstract methods that would be implemented in the subclasses.
Example:
public abstract class SuperClass {
public void processCommonLogic() {
// Common logic
// Execute specific logic in subclasses
processSpecificLogic();
}
public abstract void processCommonLogic();
}
public class ASubClass extends SuperClass {
public static int SPECIFIC_SUBCLASS_CONSTANT = 0;
public void processSpecificLogic() {
// Specific subclass logic
doSomethingWith(ASubClass.SPECIFIC_SUBCLASS_CONSTANT);
}
}
You could use the Template Method Pattern.
Have an abstract method getValue() defined in your abstract class and used within your abstract class wherever you require the value. Then each of your subclasses simply need to implement the getValue method and return the correct value for that subclass.

Private Access Specifier usage in Java Inheritance

We can access the Super Class methods which consists of operations on private data members and print the results.But why can't I print the private data members of Super Class with the SubClass object calling them in my main function? Someone please explain me.
Here is the example below.
class SuperClass1
{
private int a;
private int b;
SuperClass1(int p,int q)
{
a=p;
b=q;
}
SuperClass1(SuperClass1 obj)
{
a=obj.a;
b=obj.b;
}
SuperClass1()
{
a=-1;
b=-1;
}
int Vol()
{
return a*b;
}
}
class SubClass1 extends SuperClass1
{
int c;
SubClass1(int p,int q,int r)
{
super(p,q);
c=r;
}
SubClass1(SubClass1 obj)
{
super(obj);
c=obj.c;
}
SubClass1()
{
super();
c=-1;
}
}
public class Super
{
public static void main(String[] args)
{
SubClass1 obj1=new SubClass1();
//System.out.println("The values of obj1 are:"+obj1.a+""+obj1.b+""+obj1.c);
int vol=obj1.Vol();
System.out.println("The volume is :"+vol);
}
}
security and encapsulation
The superclass is letting its subclasses use only the public and protected methods/fields.
This allows the designer of the superclass to change the implementation of these methods if he sees it better, without breaking the subclass's correctness.
A text book example is a complex number class.
The programmer using this class only needs its functionality, he doesn't care if the implementation is with imaginary and real fields or with radius and theta fields [two distinct ways to represent complex number].
It allows the designer of the ComplexNumber class more freedom if he wants to change the class in later versions, and it also allows the user less worries: he doesn't need to take care for all the details, some are being taken care of for him.
Bonus: note you can break this behavior and access private fields and methods by using reflection - but when you do so - all bets are off, and you do it on your own responsibility.
Your question isn't very clear without an example, but I suspect that the "methods which consist of operations on private data members" aren't private. It doesn't matter that they work by accessing private data - they're not private themselves. It would be pretty pointless having access modifiers if public methods could only access other public members etc.
The whole point of encapsulation is that only the class itself should care about implementation details such as the fields in question, but can expose a contract in terms of its public (and protected) API. Code outside the class shouldn't care about the private implementation details.
JLS says:
Members of a class that are declared private are not inherited by
subclasses of that class. Only members of a class that are declared
protected or public are inherited by subclasses declared in a package
other than the one in which the class is declared.
So, to answer you question. No, private members are not accessible by subclasses.
Private members are not inherited; only the protected and public members are.
If possible, you can do one of the following:
Make the private properties of the superclass protected
Make public getters (and setters if needed) for the private properties

Why can't I declare static methods in an interface?

The topic says the most of it - what is the reason for the fact that static methods can't be declared in an interface?
public interface ITest {
public static String test();
}
The code above gives me the following error (in Eclipse, at least): "Illegal modifier for the interface method ITest.test(); only public & abstract are permitted".
There are a few issues at play here. The first is the issue of declaring a static method without defining it. This is the difference between
public interface Foo {
public static int bar();
}
and
public interface Foo {
public static int bar() {
...
}
}
The first is impossible for the reasons that Espo mentions: you don't know which implementing class is the correct definition.
Java could allow the latter; and in fact, starting in Java 8, it does!
The reason why you can't have a static method in an interface lies in the way Java resolves static references. Java will not bother looking for an instance of a class when attempting to execute a static method. This is because static methods are not instance dependent and hence can be executed straight from the class file. Given that all methods in an interface are abstract, the VM would have to look for a particular implementation of the interface in order to find the code behind the static method so that it could be executed. This then contradicts how static method resolution works and would introduce an inconsistency into the language.
I'll answer your question with an example. Suppose we had a Math class with a static method add. You would call this method like so:
Math.add(2, 3);
If Math were an interface instead of a class, it could not have any defined functions. As such, saying something like Math.add(2, 3) makes no sense.
The reason lies in the design-principle, that java does not allow multiple inheritance. The problem with multiple inheritance can be illustrated by the following example:
public class A {
public method x() {...}
}
public class B {
public method x() {...}
}
public class C extends A, B { ... }
Now what happens if you call C.x()? Will be A.x() or B.x() executed? Every language with multiple inheritance has to solve this problem.
Interfaces allow in Java some sort of restricted multiple inheritance. To avoid the problem above, they are not allowed to have methods. If we look at the same problem with interfaces and static methods:
public interface A {
public static method x() {...}
}
public interface B {
public static method x() {...}
}
public class C implements A, B { ... }
Same problem here, what happen if you call C.x()?
Static methods are not instance methods. There's no instance context, therefore to implement it from the interface makes little sense.
Now Java8 allows us to define even Static Methods in Interface.
interface X {
static void foo() {
System.out.println("foo");
}
}
class Y implements X {
//...
}
public class Z {
public static void main(String[] args) {
X.foo();
// Y.foo(); // won't compile because foo() is a Static Method of X and not Y
}
}
Note: Methods in Interface are still public abstract by default if we don't explicitly use the keywords default/static to make them Default methods and Static methods resp.
There's a very nice and concise answer to your question here. (It struck me as such a nicely straightforward way of explaining it that I want to link it from here.)
It seems the static method in the interface might be supported in Java 8, well, my solution is just define them in the inner class.
interface Foo {
// ...
class fn {
public static void func1(...) {
// ...
}
}
}
The same technique can also be used in annotations:
public #interface Foo {
String value();
class fn {
public static String getValue(Object obj) {
Foo foo = obj.getClass().getAnnotation(Foo.class);
return foo == null ? null : foo.value();
}
}
}
The inner class should always be accessed in the form of Interface.fn... instead of Class.fn..., then, you can get rid of ambiguous problem.
An interface is used for polymorphism, which applies to Objects, not types. Therefore (as already noted) it makes no sense to have an static interface member.
Java 8 Had changed the world you can have static methods in interface but it forces you to provide implementation for that.
public interface StaticMethodInterface {
public static int testStaticMethod() {
return 0;
}
/**
* Illegal combination of modifiers for the interface method
* testStaticMethod; only one of abstract, default, or static permitted
*
* #param i
* #return
*/
// public static abstract int testStaticMethod(float i);
default int testNonStaticMethod() {
return 1;
}
/**
* Without implementation.
*
* #param i
* #return
*/
int testNonStaticMethod(float i);
}
Illegal combination of modifiers : static and abstract
If a member of a class is declared as static, it can be used with its class name which is confined to that class, without creating an object.
If a member of a class is declared as abstract, you need to declare the class as abstract and you need to provide the implementation of the abstract member in its inherited class (Sub-Class).
You need to provide an implementation to the abstract member of a class in sub-class where you are going to change the behaviour of static method, also declared as abstract which is a confined to the base class, which is not correct
Since static methods can not be inherited . So no use placing it in the interface. Interface is basically a contract which all its subscribers have to follow . Placing a static method in interface will force the subscribers to implement it . which now becomes contradictory to the fact that static methods can not be inherited .
With Java 8, interfaces can now have static methods.
For example, Comparator has a static naturalOrder() method.
The requirement that interfaces cannot have implementations has also been relaxed. Interfaces can now declare "default" method implementations, which are like normal implementations with one exception: if you inherit both a default implementation from an interface and a normal implementation from a superclass, the superclass's implementation will always take priority.
Perhaps a code example would help, I'm going to use C#, but you should be able to follow along.
Lets pretend we have an interface called IPayable
public interface IPayable
{
public Pay(double amount);
}
Now, we have two concrete classes that implement this interface:
public class BusinessAccount : IPayable
{
public void Pay(double amount)
{
//Logic
}
}
public class CustomerAccount : IPayable
{
public void Pay(double amount)
{
//Logic
}
}
Now, lets pretend we have a collection of various accounts, to do this we will use a generic list of the type IPayable
List<IPayable> accountsToPay = new List<IPayable>();
accountsToPay.add(new CustomerAccount());
accountsToPay.add(new BusinessAccount());
Now, we want to pay $50.00 to all those accounts:
foreach (IPayable account in accountsToPay)
{
account.Pay(50.00);
}
So now you see how interfaces are incredibly useful.
They are used on instantiated objects only. Not on static classes.
If you had made pay static, when looping through the IPayable's in accountsToPay there would be no way to figure out if it should call pay on BusinessAcount or CustomerAccount.

Categories

Resources