Related
In my codebase, I found a class like this:
public final class Klass
{
private static final long LONG_NUMBER = 10.0;
private Klass() {}
public static double calcSomethingUsingLongNumberAndParam(double param)
{
...
return something;
}
}
My IDE (IntelliJ IDEA) offers one 'improvement' to this class - change it to an enum. As a test, I made the change, and noted no other refactors done on any of the member fields or methods, not to any calls to the static methods contained.
Here is the generated Enum:
public enum Klass
{
;
private static final long LONG_NUMBER = 10.0;
private Klass() {}
public static double calcSomethingUsingLongNumberAndParam(double param)
{
...
return something;
}
}
Is there a benefit to changing a final class to an enum, or is this a quirk of the IDE?
My answer originally said that sure there are benefits, enums supersede old-style POJO singletons (which this is a special case of) in almost every way. However, it depends a bit on the use case and actual code involved. If you just replace "final class" with "enum", as IDE seems to be doing in this case, the benefits are minimal. Also, one of the main benefits of using enum is a better type checking for finite values, but since you seem to be using only a single, numeric value and it is private, it's of no benefit here.
Pros on using an enum vs. constant utility class:
Enums get away with almost the same functionality with less code - you don't need to declare functions or values as static, nor do you need a private constructor, which are just boilerplate that enum offers out of the box
it is immediately clear with enums that they are not meant to be instantiated, whereas for a class like this, it might need more investigation and a look at its details as a whole
with a class like this it is far easier for someone updating the code to mess up the singleton pattern by accident if he/she doesn't notice it's meant to be that way
Cons:
enum class itself are effectively final, but their internal design depends on the possibility to make subclasses for the enum values, so their protection from subclassing seems to me a bit hacky.
So, if this class is part of interface offered as an external library and we can be quite confident no one will change its own implementation, it is actually a bit more safe than using an enum here. However, if this code is maintained (especially by different developers) - and any code should be, I would argue an enum has more pros to offer, as it more clearly communicates its intent. Even the only con I could come up with, removal of protection from subclassing, seems quite marginal as enums are effectively final anyway outside their defining class.
For more discussion on the benefits of enums, see What are enums and why are they useful?. There is also another discussion on the benefits of having a final keyword in a constant utility class such as yours: Final Keyword in Constant utility class - the conclusion I get from that discussion is that the only benefit is that it is explicitly forbidden to subclass it, which wouldn't work anyway since you wouldn't be able to override the static stuff.
TLDR; recommendation to replace with enum seems reasonable, at least if you omit the things you don't have to explicitly declare with enums. However the differences are related to the readability and maintainability, not any difference in behaviour.
There is no outright benefit to changing this class to an enum.
The only thing it affords you is the ability to omit the private constructor (and the final on the class).
But you'd also need either a single value (that you don't need), or just have a random hanging ; to separate the (empty) value list from the rest of the class body.
What is best practice in Java 8 when I need a bunch of stateless utility methods. Is it right to have an interface that will not be implemented by anyone i.e. public interface Signatures and public interface Environments, or is it better to do it the old way - have public final class Signatures and public final class Environments with private constructors || enums?
The main purpose of interfaces is to provide a type and a vocabulary of operations (methods) on that type. They're useful and flexible because they allow multiple implementations, and indeed they are designed to allow implementations that are otherwise unrelated in the class hierarchy.
The question asks,
Is it right to have an interface that will not be implemented by anyone...?
This seems to me to cut against the grain of interfaces. One would have to look around the API to determine that there are no classes that implement this interface, and that there are no producers or consumers of this interface. Somebody might be confused and try to create an implementation of the interface, but of course they wouldn't get very far. While it's possible to have a "utility interface" with all static methods, this isn't as clear as the old unconstructible final class idiom. The advantage of the latter is that the class can enforce that no instances can ever be created.
If you look at the new Java 8 APIs, you'll see that the final class idiom is still used despite the ability to add static methods on interfaces.
Static methods on interfaces have been used for things like factory methods to create instances of those interfaces, or for utility methods that have general applicability across all instances of those interfaces. For example, see the Stream and Collector interfaces in java.util.stream. Each has static factories: Stream.of(), Stream.empty(), and Collector.of().
But also note that each has companion utility classes StreamSupport and Collectors. These are pure utility classes, containing only static methods. Arguably they could be merged into the corresponding interfaces, but that would clutter the interfaces, and would blur the relationship of the methods contained in the classes. For example, StreamSupport contains a family of related static methods that are all adapters between Spliterator and Stream. Merging these into Stream would probably make things confusing.
I would use the final class. Communicates to me better that it is a helper class with some utility methods. An interface definition is something I would expect to be implemented and the methods to be there to assist someone implement the interface.
In a good object oriented design, there are not many (if any) stateless utility methods.
The best technique I've come to deal with is to use state (Objects) to deal with the function.
So instead of doing
Temperature.farenheitFromCelcius(...);
I do
public class FarenheitFromCelcius implements Function<Celcius, Farenheit> {
public Farenheit apply(Celcius celcius) {
return new Farenheit(5 * celcius.getValue() / 9 + 32);
}
}
This has a few advantages. One being that it can be unloaded from memory much more easily. Another being that you can save on the number of type identifying interfaces, you can pass utility methods between methods, and a final being that you can leverage the Java type hierarchy.
The costs are minimal. Basically you have to alter how the method is applied.
public <T> R convertTemp(T temp, Function<T, R> conversion) {
return conversion.apply(temp);
}
Naturally you'd never write a full method to encapsulate an object oriented function, but I had to show an example...
Static methods in interfaces were added with two primary purposes:
In case of poor implementation in subclasses static interface methods can be used to provide checks (e.g. if a value is null).
Avoid using general utility classes (like Collections) and calling static methods through their proper interface.
So, it is a very good practice if you intend to share functionality to the corresponding classes.
update:
If you wish to build a pure collection of functions then you may want to use the abstract class with static methods and a private constructor.
in your case I would go for the final class instead of getting the fatigue that someone might implement or inherent this. For use-cases where you want a static util interface. I guess we need a final interface for that...
public final class Util {
private Util {
throw new AssertionError("Please don't invoke me");
}
public static someUtilMethod() {}
private static someHelperUtilMethod() {}
}
Since I am trying to learn more about OOP (Java) I'm working my way through some literature where I found this 'task'. Unfortunately I am having kind of a hard time since I am pretty new to OOP and I don't have any sample solution to this. Maybe some of you can give me some input so can work my way through this.
Define a class hierarchy for these classes:
quadrilateral
convex quadrilateral
trapezoid
parallelogram
rhombus
rectangle
square
Create an instance of each class if possible
Define reasonable attributes and methods in each class
Overload and override methods
Write reasonable constructors for each class
Use modifiers (abstract, static, final, public, protected and private) in a meaningful way
How could an interface be used for this task?
01 Class hierarchy
Okay, this is simple math and you can find tons of information on the hierarchy of quadrilaterals everywhere. Here is what I did:
Creating Objects of each class is no big deal, but I still have some problems with understanding all the OOP-techniques. There are some points where I don't know what would be the better way to do it... (e.g. the square which inherits from two classes, which in java is simply not possible). Also, formulas (like calculating the surface area) would be overwritten all the time anyhow (since they are different most of the time), so why would I need inheritance anyway? Couldn't I just use an interface, use it in all of those classes an force them to implement these formulas?
Greetings - Vulpecula
In real life, you probably would be better off using an interface. Deep inheritance structures like that are often frowned upon; it's generally considered good to 'prefer composition over inheritance' (http://en.wikipedia.org/wiki/Composition_over_inheritance). You might for instance have a 'quadrilateral' interface that defines 'surface area' and 'perimeter', and then have the other shapes satisfy that interface.
If this is a homework question however, then you should probably base the class hierarchy on whatever examples your textbook/teacher have provided previously. It's not about designing robust software, it's about proving to your teacher that you learned how to do things in whatever way they think you should do them.
An abstract class as the base of a moderately complicated hierarchy is not as flexible as an interface. A class--abstract or not--forces a specific type of implementation.
Without thinking too hard about it, here's one way to start:
public interface Quadrilateral {
int getTopMillimeters();
int getLeftMillimeters();
int getRightMillimeters();
int getBottomMillimeters();
}
From this raw data, you could also define
getTopLeftAngle(), getTopRightAngle(), ...
which would all compute their values based on the lengths.
I too would emphasize composition over inheritance. The end-effect can indeed be a complex inheritance structure.
For me, composition is heirarchy of "Composer" classes, which do NOT implement the interface. Such as
public class QuadrilateralComposer {
private final int iTopMM;
private final int iBtmMM;
...
public QuadrilateralComposer(int i_topMM, int i_bottomMM, ...) {
if(i_topMM < 1) {
throw new IllegalArgumentException...
}
if(i_bottomMM < 1) {
throw new IllegalArgumentException...
}
...
iTopMM = i_topMM;
iBtmMM = i_bottomMM;
...
}
public int getTopMillimeters() {
return iTopMM;
}
...
Which is then composed by an abstract class:
public class AbstractQuadrilateral implements Quadrilateral
private final QuadrilateralComposer qc;
public AbstractQuadrilateral(int i_topLen, int i_bottomLen, ...) {
gc = new QuadrilateralComposer(i_topLen, i_bottomLen, ...);
}
public int getTopLength() {
return gc.getTopLength();
}
...
Abstract classes never extend other abstract classes, they only use internal Composers (and actually implement the interface). On the other end, Composers only extend Composers, and use other composers internally.
(Three notes: Protected functions are in the Composer as public function_4prot() and are implemented as protected function(), which call the _4prot version. And sometimes the abstract class can indeed implement everything in the interface. In this case, it would be concrete [non-abstract] and be named "SimpleXYZ", instead of "AbstractXYZ". Finally, static utility functions reside in the Composer.)
If EVERY interface is designed in this way, then ANY class can easily implement ANY interface, regardless which class they must actually extend. If abstract classes extend other abstract classes, that is a lot more work for classes that need to implement the interface, but happen to--and have to--extend something else.
This is not what you asked, but learning this concept changed my code for the WAY better. Seeing it mentioned in the accepted answer made me think through all of it. I've actually been slowly drifting away from inheritance to composition over the past few years, and after reading Effective Java, it was the final nail in the inheritance coffin, as it were.
Okay, the plan now is that I am trying to resolve this without any interface first. So here's the map of inheritance:
I am ignoring the fact, that the square is not only a rectange but also a rhombus.
The abstract class (quadrilateral) will define (but not implement) methods for calculating 'surface area' and 'perimeter'. Overriding methods is easy since every shape has different formumals for calculation but I am not really sure where I could use the overloading feature.
One more thing: Using an interface, would this be the desired way?
I am reading a book about Java and it says that you can declare the whole class as final. I cannot think of anything where I'd use this.
I am just new to programming and I am wondering if programmers actually use this on their programs. If they do, when do they use it so I can understand it better and know when to use it.
If Java is object oriented, and you declare a class final, doesn't it stop the idea of class having the characteristics of objects?
First of all, I recommend this article: Java: When to create a final class
If they do, when do they use it so I can understand it better and know when to use it.
A final class is simply a class that can't be extended.
(It does not mean that all references to objects of the class would act as if they were declared as final.)
When it's useful to declare a class as final is covered in the answers of this question:
Good reasons to prohibit inheritance in Java?
If Java is object oriented, and you declare a class final, doesn't it stop the idea of class having the characteristics of objects?
In some sense yes.
By marking a class as final you disable a powerful and flexible feature of the language for that part of the code. Some classes however, should not (and in certain cases can not) be designed to take subclassing into account in a good way. In these cases it makes sense to mark the class as final, even though it limits OOP. (Remember however that a final class can still extend another non-final class.)
In Java, items with the final modifier cannot be changed!
This includes final classes, final variables, and final methods:
A final class cannot be extended by any other class
A final variable cannot be reassigned another value
A final method cannot be overridden
One scenario where final is important, when you want to prevent inheritance of a class, for security reasons. This allows you to make sure that code you are running cannot be overridden by someone.
Another scenario is for optimization: I seem to remember that the Java compiler inlines some function calls from final classes. So, if you call a.x() and a is declared final, we know at compile-time what the code will be and can inline into the calling function. I have no idea whether this is actually done, but with final it is a possibility.
The best example is
public final class String
which is an immutable class and cannot be extended.
Of course, there is more than just making the class final to be immutable.
If you imagine the class hierarchy as a tree (as it is in Java), abstract classes can only be branches and final classes are those that can only be leafs. Classes that fall into neither of those categories can be both branches and leafs.
There's no violation of OO principles here, final is simply providing a nice symmetry.
In practice you want to use final if you want your objects to be immutable or if you're writing an API, to signal to the users of the API that the class is just not intended for extension.
Relevant reading: The Open-Closed Principle by Bob Martin.
Key quote:
Software Entities (Classes, Modules,
Functions, etc.) should be open for
Extension, but closed for
Modification.
The final keyword is the means to enforce this in Java, whether it's used on methods or on classes.
The keyword final itself means something is final and is not supposed to be modified in any way. If a class if marked final then it can not be extended or sub-classed. But the question is why do we mark a class final? IMO there are various reasons:
Standardization: Some classes perform standard functions and they are not meant to be modified e.g. classes performing various functions related to string manipulations or mathematical functions etc.
Security reasons: Sometimes we write classes which perform various authentication and password related functions and we do not want them to be altered by anyone else.
I have heard that marking class final improves efficiency but frankly I could not find this argument to carry much weight.
If Java is object oriented, and you declare a class final, doesn't it
stop the idea of class having the characteristics of objects?
Perhaps yes, but sometimes that is the intended purpose. Sometimes we do that to achieve bigger benefits of security etc. by sacrificing the ability of this class to be extended. But a final class can still extend one class if it needs to.
On a side note we should prefer composition over inheritance and final keyword actually helps in enforcing this principle.
final class can avoid breaking the public API when you add new methods
Suppose that on version 1 of your Base class you do:
public class Base {}
and a client does:
class Derived extends Base {
public int method() { return 1; }
}
Then if in version 2 you want to add a method method to Base:
class Base {
public String method() { return null; }
}
it would break the client code.
If we had used final class Base instead, the client wouldn't have been able to inherit, and the method addition wouldn't break the API.
A final class is a class that can't be extended. Also methods could be declared as final to indicate that cannot be overridden by subclasses.
Preventing the class from being subclassed could be particularly useful if you write APIs or libraries and want to avoid being extended to alter base behaviour.
In java final keyword uses for below occasions.
Final Variables
Final Methods
Final Classes
In java final variables can't reassign, final classes can't extends and final methods can't override.
Be careful when you make a class "final". Because if you want to write an unit test for a final class, you cannot subclass this final class in order to use the dependency-breaking technique "Subclass and Override Method" described in Michael C. Feathers' book "Working Effectively with Legacy Code". In this book, Feathers said, "Seriously, it is easy to believe that sealed and final are a wrong-headed mistake, that they should never have been added to programming languages. But the real fault lies with us. When we depend directly on libraries that are out of our control, we are just asking for trouble."
If the class is marked final, it means that the class' structure can't be modified by anything external. Where this is the most visible is when you're doing traditional polymorphic inheritance, basically class B extends A just won't work. It's basically a way to protect some parts of your code (to extent).
To clarify, marking class final doesn't mark its fields as final and as such doesn't protect the object properties but the actual class structure instead.
TO ADDRESS THE FINAL CLASS PROBLEM:
There are two ways to make a class final. The first is to use the keyword final in the class declaration:
public final class SomeClass {
// . . . Class contents
}
The second way to make a class final is to declare all of its constructors as private:
public class SomeClass {
public final static SOME_INSTANCE = new SomeClass(5);
private SomeClass(final int value) {
}
Marking it final saves you the trouble if finding out that it is actual a final, to demonstrate look at this Test class. looks public at first glance.
public class Test{
private Test(Class beanClass, Class stopClass, int flags)
throws Exception{
// . . . snip . . .
}
}
Unfortunately, since the only constructor of the class is private, it is impossible to extend this class. In the case of the Test class, there is no reason that the class should be final. The Test class is a good example of how implicit final classes can cause problems.
So you should mark it final when you implicitly make a class final by making it's constructor private.
One advantage of keeping a class as final :-
String class is kept final so that no one can override its methods and change the functionality. e.g no one can change functionality of length() method. It will always return length of a string.
Developer of this class wanted no one to change functionality of this class, so he kept it as final.
The other answers have focused on what final class tells the compiler: do not allow another class to declare it extends this class, and why that is desirable.
But the compiler is not the only reader of the phrase final class. Every programmer who reads the source code also reads that. It can aid rapid program comprehension.
In general, if a programmer sees Thing thing = that.someMethod(...); and the programmer wants to understand the subsequent behaviour of the object accessed through the thing object-reference, the programmer must consider the Thing class hierarchy: potentially many types, scattered over many packages. But if the programmer knows, or reads, final class Thing, they instantly know that they do not need to search for and study so many Java files, because there are no derived classes: they need study only Thing.java and, perhaps, it's base classes.
Yes, sometimes you may want this though, either for security or speed reasons. It's done also in C++. It may not be that applicable for programs, but moreso for frameworks.
http://www.glenmccl.com/perfj_025.htm
think of FINAL as the "End of the line" - that guy cannot produce offspring anymore. So when you see it this way, there are ton of real world scenarios that you will come across that requires you to flag an 'end of line' marker to the class. It is Domain Driven Design - if your domain demands that a given ENTITY (class) cannot create sub-classes, then mark it as FINAL.
I should note that there is nothing stopping you from inheriting a "should be tagged as final" class. But that is generally classified as "abuse of inheritance", and done because most often you would like to inherit some function from the base class in your class.
The best approach is to look at the domain and let it dictate your design decisions.
As above told, if you want no one can change the functionality of the method then you can declare it as final.
Example: Application server file path for download/upload, splitting string based on offset, such methods you can declare it Final so that these method functions will not be altered. And if you want such final methods in a separate class, then define that class as Final class. So Final class will have all final methods, where as Final method can be declared and defined in non-final class.
Let's say you have an Employee class that has a method greet. When the greet method is called it simply prints Hello everyone!. So that is the expected behavior of greet method
public class Employee {
void greet() {
System.out.println("Hello everyone!");
}
}
Now, let GrumpyEmployee subclass Employee and override greet method as shown below.
public class GrumpyEmployee extends Employee {
#Override
void greet() {
System.out.println("Get lost!");
}
}
Now in the below code have a look at the sayHello method. It takes Employee instance as a parameter and calls the greet method hoping that it would say Hello everyone! But what we get is Get lost!. This change in behavior is because of Employee grumpyEmployee = new GrumpyEmployee();
public class TestFinal {
static Employee grumpyEmployee = new GrumpyEmployee();
public static void main(String[] args) {
TestFinal testFinal = new TestFinal();
testFinal.sayHello(grumpyEmployee);
}
private void sayHello(Employee employee) {
employee.greet(); //Here you would expect a warm greeting, but what you get is "Get lost!"
}
}
This situation can be avoided if the Employee class was made final. Just imagine the amount of chaos a cheeky programmer could cause if String Class was not declared as final.
Final class cannot be extended further. If we do not need to make a class inheritable in java,we can use this approach.
If we just need to make particular methods in a class not to be overridden, we just can put final keyword in front of them. There the class is still inheritable.
Final classes cannot be extended. So if you want a class to behave a certain way and don't someone to override the methods (with possibly less efficient and more malicious code), you can declare the whole class as final or specific methods which you don't want to be changed.
Since declaring a class does not prevent a class from being instantiated, it does not mean it will stop the class from having the characteristics of an object. It's just that you will have to stick to the methods just the way they are declared in the class.
Android Looper class is a good practical example of this.
http://developer.android.com/reference/android/os/Looper.html
The Looper class provides certain functionality which is NOT intended to be overridden by any other class. Hence, no sub-class here.
I know only one actual use case: generated classes
Among the use cases of generated classes, I know one: dependency inject e.g. https://github.com/google/dagger
Object Orientation is not about inheritance, it is about encapsulation. And inheritance breaks encapsulation.
Declaring a class final makes perfect sense in a lot of cases. Any object representing a “value” like a color or an amount of money could be final. They stand on their own.
If you are writing libraries, make your classes final unless you explicitly indent them to be derived. Otherwise, people may derive your classes and override methods, breaking your assumptions / invariants. This may have security implications as well.
Joshua Bloch in “Effective Java” recommends designing explicitly for inheritance or prohibiting it and he notes that designing for inheritance is not that easy.
Why is it a good practice to mark a class with only private constructors as final? My guess is, it is to let other programmers know that it cannot be sub-classed.
It is often considered (e.g. by Josh Bloch and the designers of C#) good practice to mark everything as final unless you have an explicit reason not to. Assuming you mean class, you're correct that a class with only private constructors can't be subclassed. Thus, the final could be considered redundant, but as you say it has value for documentation. As Marc suggests, it may also aid optimization.
Making a class final has some (small) performance gain, because the JIT compiler can inline functionality from that class. I don't know if that qualifies as 'good practice', but I see the advantages.
You mean "a class with private constructor" do you?
A final class can't be subclassed. This may represent a design decision. Not all classes are designed to be subclassed, so if yours is not, it is best to mark it explicitly, to avoid subtle bugs later.
A class with private constructors only can't be instantiated by the outside world (neither subclassed). This may be useful for e.g. singletons, or classes where you want to control what instances of the class are created. E.g. before Java5, the typesafe enum pattern used this.
We mark the class as final class by making constructor as private, to avoid sub-classing.
This is good practice, in cases where we don’t want people to override our class methods and change the functionality or add the functions to our class.
For example, classes String and Math are final classes, which we can’t extend or subclass, this is to make sure that no one will change their behavior.
A final class with private constructor:
Class can not have sub-classes, we can not extent final class.
Class having private constructor, we can not create the object of that class.
It means other methods of the class will be static, so that class can access them.