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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With