What do you think of the following way to simulate a static class in java?
You can add non static methods but you wouldn't be able to call them.
/**
* Utility class: this class contains only static methods and behaves as a static class.
*/
// ... prevent instantiation with abstract keyword
public abstract class Utilities
{
// ... prevent inheritance with private constructor
private Utilities() {}
// ... all your static methods here
public static Person convert(String foo) {...}
}
That is the usual way. However, there is not need for the abstract keyword. Using a private constructor is sufficient because
it prevents the creation of objects (from outside the class)
it prevents inheritance
The abstract keyword suggests the user that users of the class might implemented the class what is not the case here.
Item 4 in Effective Java (a very... effective book) says:
// Noninstantiable utility class
public final class Utility {
private Utility() {
throw new AssertionError();
}
}
because the explicit costructor is private:
you cannot instantiate it
you cannot extend it (as if it was declared as final)
The AssertionError isn't required but it provides another small benefit: it prevents that the costructior is accidentally invoked from within the class.
You can also create a specific annotation, like #BagOfFunction, and annotate your class:
#BagOfFunctions
public final class Utility {
private Utility() {
throw new AssertionError();
}
}
basically you trade a comment for a self-documenting annotation.
My FindBugs plugin suggests rather final class instead of abstract class. And I use that in my project. It seems to be a widespread idiom if it became a rule that is checked by FindBugs.
i would say, if you habe already a private constructor
private Utilities() {}
the abstract keyword is not neccessary. rather make it final.
the difference to your version is marginal, for any practical means.
I prefer making such classes final, but not abstract. Though it is just a matter of personal style.
By the way, I suppose it is still possible to call its instance methods if you put some energies. E.g. one can try using objenesis to create instance of class.
I'll have to agree with those above. Use "final" instead of "abstract". Remember, words like "final" and "abstract" are as much a means of communicating with your fellow programmers as they are instructions to the machine. Abstract implies that there will be descendant classes later, whereas final decidedly means that you will not, save through refactoring, see anything descended of this class (which is your intended meaning).
Further, in most standards I've seen, and consistently in my company, it is considered best practice to make the abstract class something which is specifically left unused, save as a parent of other classes. "Abstract" is treated as "blueprint" or "general structure", you would never drive an "abstract" car. On the other hand, final classes are instantiated perpetually, especially with Factory patterns.
My suggestion is: prevent incorrect use (i.e. instantiation) by placing javadocs
Isn't that simpler? I think your teammates are able to read ;)
Related
I have just found a static nested interface in our code-base.
class Foo {
public static interface Bar {
/* snip */
}
/* snip */
}
I have never seen this before. The original developer is out of reach. Therefore I have to ask SO:
What are the semantics behind a static interface? What would change, if I remove the static? Why would anyone do this?
The static keyword in the above example is redundant (a nested interface is automatically "static") and can be removed with no effect on semantics; I would recommend it be removed. The same goes for "public" on interface methods and "public final" on interface fields - the modifiers are redundant and just add clutter to the source code.
Either way, the developer is simply declaring an interface named Foo.Bar. There is no further association with the enclosing class, except that code which cannot access Foo will not be able to access Foo.Bar either. (From source code - bytecode or reflection can access Foo.Bar even if Foo is package-private!)
It is acceptable style to create a nested interface this way if you expect it to be used only from the outer class, so that you do not create a new top-level name. For example:
public class Foo {
public interface Bar {
void callback();
}
public static void registerCallback(Bar bar) {...}
}
// ...elsewhere...
Foo.registerCallback(new Foo.Bar() {
public void callback() {...}
});
The question has been answered, but one good reason to use a nested interface is if its function is directly related to the class it is in. A good example of this is a Listener. If you had a class Foo and you wanted other classes to be able to listen for events on it, you could declare an interface named FooListener, which is ok, but it would probably be more clear to declare a nested interface and have those other classes implement Foo.Listener (a nested class Foo.Event isn't bad along with this).
Member interfaces are implicitly static. The static modifier in your example can be removed without changing the semantics of the code. See also the the Java Language Specification 8.5.1. Static Member Type Declarations
An inner interface has to be static in order to be accessed. The interface isn't associated with instances of the class, but with the class itself, so it would be accessed with Foo.Bar, like so:
public class Baz implements Foo.Bar {
...
}
In most ways, this isn't different from a static inner class.
Jesse's answer is close, but I think that there is a better code to demonstrate why an inner interface may be useful. Look at the code below before you read on. Can you find why the inner interface is useful? The answer is that class DoSomethingAlready can be instantiated with any class that implements A and C; not just the concrete class Zoo. Of course, this can be achieved even if AC is not inner, but imagine concatenating longer names (not just A and C), and doing this for other combinations (say, A and B, C and B, etc.) and you easily see how things go out of control. Not to mention that people reviewing your source tree will be overwhelmed by interfaces that are meaningful only in one class.So to summarize, an inner interface enables the construction of custom types and improves their encapsulation.
class ConcreteA implements A {
:
}
class ConcreteB implements B {
:
}
class ConcreteC implements C {
:
}
class Zoo implements A, C {
:
}
class DoSomethingAlready {
interface AC extends A, C { }
private final AC ac;
DoSomethingAlready(AC ac) {
this.ac = ac;
}
}
To answer your question very directly, look at Map.Entry.
Map.Entry
also this may be useful
Static Nested Inerfaces blog Entry
Typically I see static inner classes. Static inner classes cannot reference the containing classes wherease non-static classes can. Unless you're running into some package collisions (there already is an interface called Bar in the same package as Foo) I think I'd make it it's own file. It could also be a design decision to enforce the logical connection between Foo and Bar. Perhaps the author intended Bar to only be used with Foo (though a static inner interface won't enforce this, just a logical connection)
If you will change class Foo into interface Foo the "public" keyword in the above example will be also redundant as well because
interface defined inside another interface will implicitly public
static.
In 1998, Philip Wadler suggested a difference between static interfaces and non-static interfaces.
So far as I can see, the only difference in making an
interface non-static is that it can now include non-static inner
classes; so the change would not render invalid any existing Java
programs.
For example, he proposed a solution to the Expression Problem, which is the mismatch between expression as "how much can your language express" on the one hand and expression as "the terms you are trying to represent in your language" on the other hand.
An example of the difference between static and non-static nested interfaces can be seen in his sample code:
// This code does NOT compile
class LangF<This extends LangF<This>> {
interface Visitor<R> {
public R forNum(int n);
}
interface Exp {
// since Exp is non-static, it can refer to the type bound to This
public <R> R visit(This.Visitor<R> v);
}
}
His suggestion never made it in Java 1.5.0. Hence, all other answers are correct: there is no difference to static and non-static nested interfaces.
In Java, the static interface/class allows the interface/class to be used like a top-level class, that is, it can be declared by other classes. So, you can do:
class Bob
{
void FuncA ()
{
Foo.Bar foobar;
}
}
Without the static, the above would fail to compile. The advantage to this is that you don't need a new source file just to declare the interface. It also visually associates the interface Bar to the class Foo since you have to write Foo.Bar and implies that the Foo class does something with instances of Foo.Bar.
A description of class types in Java.
Static means that any class part of the package(project) can acces it without using a pointer. This can be usefull or hindering depending on the situation.
The perfect example of the usefullnes of "static" methods is the Math class. All methods in Math are static. This means you don't have to go out of your way, make a new instance, declare variables and store them in even more variables, you can just enter your data and get a result.
Static isn't always that usefull. If you're doing case-comparison for instance, you might want to store data in several different ways. You can't create three static methods with identical signatures. You need 3 different instances, non-static, and then you can and compare, caus if it's static, the data won't change along with the input.
Static methods are good for one-time returns and quick calculations or easy obtained data.
I just want to know that can i have 2 classes A and B.
I don't want to allow class B to extends class A.
What technique should i apply in class A so class B cannot inherit class A.
Don't want to make class A final. Any other solution instead of making class A final?
In fact, the practice that I try to follow, and that Josh Bloch recommends, in his Effective Java book, is exactly the inverse rule of the one you've been told: Unless you have thought about inheritance, designed your class to be inherited, and documented how your class must be inherited, you should always disable inheritance.
I would recommend reading this chapter of Effective Java (you won't regret buying it), and showing it to the person who told you about this rule.
The most obvious reason to disallow inheritance is immutability. An immutable object is simple to use (only one state), can be cached, shared between many objects, and is inherently thread-safe. If the class is inheritable, anyone can extend the class and make it mutable by adding mutable attributes.
https://stackoverflow.com/a/10464466/5010396
This is not possible in "nice ways". The java language allows you to either have the final keyword on your class definition, or to not have it.
As pointed out by others: you can make all constructors private, then subclassing becomes practically impossible, as the subclass constructors have no super class constructor to call.
In case you need to instantiate A, you could still have a factory method, like:
public class A {
private A() { ... }
private A(String foo) { ... }
public static A newInstance(String foo) { return new A(foo); }
for example.
But keep in mind: code is written for your human readers. If your intent is to have a final class, then the correct answer is to use that keyword final.
Plus: making your class final allows the JIT to do a few more things, as it doesn't have to worry about polymorphism at any point (so it can directly inline method code, without any additional checks). So using final can result in slightly improved performance. On the other hand, it limits your ability to unit test things (for example: standard Mockito can't mock final classes).
You can mark the constructor of A class as private. :)
PS: If you also want to avoid reflection attacks then throw some Error from constructor
and also mark it private.
You have an option to restrict in constructor like this.
if (this.getClass() != MyClass.class) {
throw new RuntimeException("Subclasses not allowed");
}
For further details check the post.
https://stackoverflow.com/a/451229/6742601
I don't understand the specific use case of your requirement but this could work.
If you are open to make changes in B
In B's every constructor check for is it is an instance of A then throw an error.
if(A.class.isAssignableFrom(B.class)) {
System.out.println(true);
throw new IllegalStateException();
}
else
System.out.println(false);
You can do one of the following to avoid inheritance without using final keyword:
Use private constructor(s).
Mark every method final so children can't override them.
Throw Runtime exception in the constructor if want to limit inheritance for some unwanted children (although v.rude) e.g
if (this.getClass() != FavoriteChild.class) throw new RuntimeException("Not Allowed")
Why should we declare an interface inside a class in Java?
For example:
public class GenericModelLinker implements IModelLinker {
private static final Logger LOG =LoggerFactory.getLogger(GenericModelLinker.class);
private String joinAsPropertyField;
private boolean joinAsListEntry;
private boolean clearList;
private List<Link> joins;
//instead of a scalar property
private String uniqueProperty;
public interface Link {
Object getProperty(IAdaptable n);
void setProperty(IAdaptable n, Object value);
}
}
When you want to gather some fields in an object in order to emphasize a concept, you could either create an external class, or an internal (called either nested (static ones) or inner).
If you want to emphasize the fact that this cooperative class makes strictly no sense (has no use) outside the original object use, you could make it nested/inner.
Thus, when dealing with some hierarchy, you can describe a "nested" interface, which will be implemented by the wrapping class's subclasses.
In the JDK, the most significant example would be Map.Entry inner interface, defined within Map interface and implemented by various ways by HashMap, LinkedHashMap etc...
And of course, Map.Entry needed to be declared as public in order to be accessible while iterating the map wherever the code is.
If the interface definition is small and the interface will only be used by clients of the class it's defined in, it's a good way to organize the code. Otherwise, the interface should be defined in its own file.
This is inner interface. Java programming language allows defining inner classes and interfaces. This is typically useful if you want to limit visibility of this class or interface by scope of current outer class.
Some people use this mechanism for creating a kind of namespace. IMHO this is abuse of the language feature (in most cases).
To encapsulate behavior in a generic and resuable way.
Apart from nice example of Map.Entry used by Map implementation classes another good example is implementation of Strategy Pattern, where a execution strategy is evaluated and applied internally.
class Test
{
..
interface Cipher {
doAction();
}
class RAMPCipher implements Cipher{}
class DiskCipher implements Cipher{}
..
}
Inside your class you may need multiple implementations of an interface, which is only relevant to this particular class. In that case make it an inner interface, rather than a public / package-private one.
Only an interface inside a class can be declared private or protected. Sometimes, that makes sense, when the interface is only appropriate for use inside the outer class (or its subclasses).
In Java what is the purpose of using private constructor in an abstract class?
In a review I got this question, and I am curious, for what situation we need to use the constructor in such way?
I think it can be used in pair with another constructor in abstract class, but this is very trivial. Also it can be used for constructing static inner classes which will excend abstract class.
Maybe there is more elegant usage?
If the private constructor is the only constructor of the class, then the reason is clear: to prevent subclassing. Some classes serve only as holders for static fields/methods and do not want to be either instantiated or subclassed. Note that the abstract modifier is in this case redundant—with or without it there would be no instantiation possible. As #JB Nizet notes below, the abstract modifier is also bad practice because it sends wrong signals to the class's clients. The class should in fact have been final.
There is another use case, quite rare though: you can have an abstract class with only private constructors that contains its own subclasses as nested classes. This idiom makes sure those nested classes are the only subclasses. In fact, enums in Java use just this idiom.
If there are other constructors around, well then there's really nothing special about the private constructor. It gets used in an abstract class just as in any other.
Only thing I can think of is reusing common code shared by the other (protected) constructors. They could then call the private constructor in their first line.
Sometimes, the default no-arg constructor is made private, and another constructor which accepts arguments is provided. This constructor might then invoke other private constructor(s) . This forces implementations to supply these arguments, which might ensure some variable is always initialized, although this is not common practice (in my experience). If this is the requirement, you would be better off checking your variables and throwing an IllegalArgumentExeption, explaining why the variable needs to be initialized.
If you create an abstract class with only private constructors, the class is practically useless as no instances can ever be created. If the intention is to create a utility class with only static methods (like the Math class in the java.lang package), private constructors are acceptable, however the class should be marked final instead, as marking the class as abstract implies the class is to be extended.
As mentioned, to be used as a common, internal-use only constructor.
Abstract or not abstract, it's not uncommon to declare a private default constructor on a class containing only static public methods [helper methods] to prevent instantiating the class.
no other elegant use is possible
A private constructor in an abstract class can also serve the purpose of sealed classes (like in Scala or Kotlin etc.). Since you can still provide subclasses from within the abstract class, but outsiders cannot extend/implement (as #Marko Topolnik answered).
It does look like we will be getting sealed interface to more cleanly support this. See https://openjdk.java.net/jeps/8222777
A final class with only private constructors is a design used by singletons and multitons.
An abstract class which has only private constructors is the only way I've seen to prevent a class from being instantiated. I have seen it used to create utility classes (which only have static methods and/or members).
As for setting up user expectations I see that https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html states "Abstract classes cannot be instantiated, but they can be subclassed." I note that it does not state any intention that they are expected to be subclassed.
I also note however that viewing some Java source code I find the following designs are used (none of which are abstract classes with only private constructors):
Final utility classes with private constructors
http://developer.classpath.org/doc/java/lang/Math-source.html
http://developer.classpath.org/doc/java/lang/System-source.html
Final utility classes with private constructors which
throw exceptions
http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Objects.java
Neither abstract nor final utility classes with private constructors
http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/ArrayPrefixHelpers.java
http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Arrays.java
https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Collections.java
http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/FormattableFlags.java
Looks like a utility, but apparently can be instantiated (no private
constructors)
http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/ArraysParallelSortHelpers.java
Is there any other method of stopping inheritance of a class apart from declaring it as final or by declaring its constructor as private?
A comment
//Do not inherit please
Two more options:
make each method final, so people can't override them. You avoid accidental calling of methods from subclass this way. This doesn't stop subclassing though.
put check into constructor for class:
if (this.getClass() != MyClass.class) {
throw new RuntimeException("Subclasses not allowed");
}
Then nobody will be able to instantiate subclass of your class.
(Not that I suggest using these techniques, it just came to my mind. I would use final class and/or private constructor)
Use final
Use private constructors
Use a comment:
// do not inherit
Use a javadoc comment
Make every method final, so people can't override them
Use a runtime check in the class constructor:
if (this.getClass() != MyClass.class) {
throw new RuntimeException("Subclasses not allowed");
}
Final was created to solve this problem.
Make your constructors private and provide factory functions to create instances.
This can be especially helpful when you want to choose an appropriate implementation from multiple, but don't want to allow arbitrary subclassing as in
abstract class Matrix {
public static Matrix fromDoubleArray(double[][] elemens) {
if (isSparse(elements)) {
return new SparseMatrix(elements);
} else {
return new DenseMatrix(elements);
}
}
private Matrix() { ... } // Even though it's private, inner sub-classes can still use it
private static class SparseMatrix extends Matrix { ... }
}
Using final is the canonical way.
public final class FinalClass {
// Class definition
}
If you want to prevent individual methods from being overridden, you can declare them as final instead. (I'm just guessing here, as to why you would want to avoid making the whole class final.)
I'd have to say it's typically bad form. Though there are almost always cases where something is valid, I'd have to saying stopping inheritance in an OO world is normally not a good idea. Read up on the Open-Closed Principle and here. Protect your functionality but don't make it impossible for the guy who comes in and supports it...
Without using a final class, you can basically make all the constructors private:
public class A {
private A() {} //Overriding default constructor of Java
}
Which although will also make this class abstract-ish by disallowing creating an object of this class, yet as any inheritance requires super(); in the constructor, and because the constructor is private, a compilation error will be the maximum you can get when one tries to inherit that class.
Yet, I would recommend using final instead as it is less code and includes the option of creating objects.