Why final classes cannot be overridden in java? [duplicate] - java

This question already has answers here:
What is the point of "final class" in Java?
(24 answers)
Closed 9 years ago.
I was asked about the reason of why a final class cannot be overridden. I tried to explain that it is more of design approach where by you don't want your class to be extended or methods to be overridden and a final class also helps to make an object immutable (though there are more steps to be done rather than just declaring the class as final).
However I would like to know if there is more to thought process behind declaring a class as final or the fact that it cannot be overridden?

Because them's the rules; It's a part of the design of the language.
http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.1.1.2
As a designer you say "my class is not suitable for inheritence"; Java honours this by explicitly preventing someone from doing so.

Final class cannot be extended because Java compiler will not allow it, because Java compiler follows the rules defined by Java Language Specification which does not allow it.

final methods can't be overriden, because that's what final is designed to do: it's a sign saying "do not override this".
From Wiki
A final method cannot be overridden or hidden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.
A common misconception is that declaring a class or method as final improves efficiency by allowing the compiler to directly insert the method wherever it is called (see inline expansion). But because the method is loaded at runtime, compilers are unable to do this. Only the runtime environment and JIT compiler know exactly which classes have been loaded, and so only they are able to make decisions about when to inline, whether or not the method is final.

A final class is a class that can't be extended, thats the reason u cannot override the final class
it is also used to make the class immutable
and one good advantage of defining class as final that it improves JVM performance
see this

Related

"should be accessed in a static way" [duplicate]

This question already has answers here:
class or method alias in java
(8 answers)
Closed 3 years ago.
I have a class with a probably unnecessarily cumbersome name, that contains a lot of static methods I use elsewhere.
Rather than fill my code with a lot of
VeryUnnecessarilyLongCumbersomeName.doThingFoo();
VeryUnnecessarilyLongCumbersomeName.doThingBar();
VeryUnnecessarilyLongCumbersomeName.doThingEgg();
VeryUnnecessarilyLongCumbersomeName.doThingSpam();
I would rather have
VeryUnnecessarilyLongCumbersomeName thing = new VeryUnnecessarilyLongCumbersomeName();
thing.doThingFoo();
thing.doThingBar();
thing.doThingEgg();
thing.doThingSpam();
However, this gets the warning
"the static method doThingFoo() should be accessed in a static way."
I know there are multiple solutions here. Use better class names. Make it not static. Ignore it because it's just a warning.
But I don't actually think it should be a warning. What harm does doing it this way cause? Is there a more elegant/correct way to make my code less clunky that isn't one of the above solutions?
NOTE: I suspect this might warrant the coding-style tag and therefore be considered off-topic and get rejected. I was thinking there's room here for a question like this, however, so I leave it up to y'all.
Although it is not technically harmful because it technically works, the problem with this is it is misleading, and any values that the instance thing contains, do not actually matter at all for the results of the methods.
Typical Java Convention:
When accessing a method through an instance, one would expect the result to be dependent on the values of the instance.
When accessing a method through a Class name, one would expect the result to be independent of the values of any instance.
Your way:
You are accessing a method through an instance and expecting it to be independent of any instance.
So why use an instance for an instance independent method? That is why it is misleading. I would suggest attempting to shorten the class name rather than accessing static methods through an instance.
How about changing the VeryUnnecessarilyLongCumbersomeName class?
Static methods are there to be used without instances. They are meant to be used if you want to invoke the method without first initializing a class. The downside of using static methods is that you lose all kinds of OOP benefits; You lose virtual dispatch and subsequently polymorphism. You can never override that method in a derived class. Of course you can declare a new (static) method in a derived class, but any code that accesses it has to be aware of the entire class hierarchy and do explicit checking and casting, which is precisely what OO is supposed to avoid.
Also, it is confusing. When another programmer sees your code, he/she will think upon seeing a static he/she will assume that it will not require a valid instance to invoke the method.
TLDR; don't do it and stick with the best practices =)

Is it mandatory utility class should be final and private constructor?

By making private constructor, we can avoid instantiating class from anywhere outside. and by making class final, no other class can extend it. Why is it necessary for Util class to have private constructor and final class ?
This is not a mandate from a functional point of view or java complication or runtime. However, it's a coding standard accepted by the wider community. Even most static code review tools, like checkstyle, check that such classes have this convention followed.
Why this convention is followed is already explained in other answers and even OP covered that, but I'd like to explain it a little further.
Mostly utility classes are a collection of methods/functions which are independent of an object instance. Those are kind of like aggregate functions as they depend only on parameters for return values and are not associated with class variables of the utility class. So, these functions/methods are mostly kept static. As a result, utility classes are, ideally, classes with only static methods. Therefore, any programmer calling these methods doesn't need to instantiate the class. However, some robo-coders (maybe with less experience or interest) will tend to create the object as they believe they need to before calling its method. To avoid that, we have 3 options:
Keep educating people to not instantiate it. (No sane person can keep doing it.)
Mark the utility class as abstract: Now robo-coders will not create the object. However, reviewers and the wider java community will argue that marking the class as abstract means you want someone to extend it. So, this is also not a good option.
Private constructor: Not protected because it'll allow a child class to instantiate the object.
Now, if someone wants to add a new method for some functionality to the utility class, they don't need to extend it: they can add a new method as each method is independent and has no chance of breaking other functionalities. So, no need to override it. Also, you are not going to instantiate it, so no need to subclass it. Better to mark it final.
In summary, instantiating a utility class (new MyUtilityClass()) does not make sense. Hence the constructors should be private. And you never want to override or extend it, so mark it final.
It's not necessary, but it is convenient. A utility class is just a namespace holder of related functions and is not meant to be instantiated or subclassed. So preventing instantiation and extension sends a correct message to the user of the class.
There is an important distinction between the Java Language, and the Java Runtime.
When the java class is compiled to bytecode, there is no concept of access restriction, public, package, protected, private are equivalent. It is always possible via reflection or bytecode manipulation to invoke the private constructor, so the jvm cannot rely on that ability.
final on the other hand, is something that persists through to the bytecode, and the guarantees it provides can be used by javac to generate more efficient bytecode, and by the jvm to generate more efficient machine instructions.
Most of the optimisations this enabled are no longer relevant, as the jvm now applies the same optimisations to all classes that are monomorphic at runtime—and these were always the most important.
By default this kind of class normally is used to aggregate functions who do different this, in that case we didn't need to create a new object

When I define an interface method's parameters final do I need to repeat final in the implementations? [duplicate]

This question already has answers here:
Final arguments in interface methods - what's the point?
(5 answers)
Closed 9 years ago.
So do I need to repeat final in the case below ?
interface Foo {
void meth(final Bar bar);
}
public Baz implements Foo {
#Override
void meth(/* is it final ?*/ Bar bar){}
}
The question is not only for interface inheritance but class inheritance also - I guess the answer will be the same
Yes you do need to redeclare method parameters as final if you want the compiler to make sure these parameters are never reassigned in the current method. This holds both when overriding interface and class definitions.
The reason for this is rather simple: This is the behavior specified in the Java language specification. However, the compiler could not even check for not reassigning final parameters even if it wanted to:
The final modifier for variables in method scope is actually not translated into byte code or written elsewhere into the Java class file format. It basically disappears after the compilation of a specific class or interface and cannot be traced after this compilation. Since each class and interface is compiled independently of other classes and interfaces, the compiler or the JVM run time verifier could not make sure that final parameters were assigned with a new value in subclasses or interface implementations. It is only within the compilation of a single class where the Java compiler can assure that such assignments do not occure. The declaration of final parameters is therefore local for a class and it would not be possibility to change this behavior in the future or to find out about this feature by using run time reflection.
Using a final parameter in an abstract method signature does therefore not serve a purpose, neither a real one or a documentary one: Since Java implements method calls by call by value and not by reference, the final modifier will never effect code outside of the implementing method's scope. If a method parameter variable is reassigned is therefore merely a detail of the methods actual implementation. I would therefore personally never use it for defining abstract methods in classes or interfaces. It is allowed but meaningless.
Within non-abstract method definitions, declaring a method variable final only serves one of two purposes:
You want to use a variable inside an anonymous class's scope.
You want the compiler to check that you did not accidentaly reassign a variable. This is escpecially useful when dealing with many variables of similar type. Here, the final modifier also serves as some kind of documentation.
UPDATE: Since Java 8, a method parameter is attributed on if it is synthetic (non represented in the source code, mandated (implicitly present in the source code, e.g. the this reference for lambda expressions) or if it is final. This does however not effect overridden methods where the final declaration needs to be repeated for this flag to be set. Furthermore does the Java language not pay attention to these flags, it is only meta frameworks that read these flags to implement their logic which might react to theses flags.

Why is it that we cannot override static and final methods? [duplicate]

This question already has answers here:
Why doesn't Java allow overriding of static methods?
(22 answers)
Closed 9 years ago.
I am trying to understand why we can't override static and final methods. I do not get the purpose behind it.
final methods can't be overriden, because that's what final is designed to do: it's a sign saying "do not override this".
static methods can't be overriden, because they are never called in a polymorphic way: when you call SomeClass.foo() it will always be the foo method of SomeClass, no matter if there is another ExtendedSomeClass that has a much groovier foo method.
final is used to avoid overriding. And a static method is not associated with any instance of a class so the concept is not applicable.
The reason for not overriding static method is that Static methods are treated as global by the JVM so there are not bound to an object instance at all. Similarly final methods cant be overriddent because when you say a method as final then it mean you are saying to the JVM that this method cannot be overridden.
The wiki has a very important misconception about final. Do read that!
A final method cannot be overridden or hidden by subclasses.[2] This
is used to prevent unexpected behavior from a subclass altering a
method that may be crucial to the function or consistency of the
class.[3]
A common misconception is that declaring a class or method as final
improves efficiency by allowing the compiler to directly insert the
method wherever it is called (see inline expansion). But because the
method is loaded at runtime, compilers are unable to do this. Only the
runtime environment and JIT compiler know exactly which classes have
been loaded, and so only they are able to make decisions about when to
inline, whether or not the method is final.[4]
Static methods are covered here.
Final methods cannot be overridden because the purpose of the "final" keyword is to prevent overriding.
Final cannot be overridden because that is the purpose of the keyword, something that cannot be changed or overridden.
The purpose of inheritance and polymorphism is to have objects of same class implementing methods (not the names but the code in the methods) in different ways. And static methods cannot be accessed by objects because they are a part of the class not the instance. So there is no purpose to overriding the Static methods. And you can have a static method in subclass by the same name but that won’t be an overridden method.
If you haven't yet read about Inheritance and Polymorphism which are both features of Java, you should and also try to write the code in the question so that SO users can answer with an example.

When to use "final" keyword before a class? [duplicate]

This question already has answers here:
What is the point of "final class" in Java?
(24 answers)
Closed 9 years ago.
I know that when final keyword is used before a Class , the Class cannot be inherited by another Class.
But I have never seen its real usage in Java Coding except for immutable classes.
In which scenarios it will be really required to use final keyword before a Class?
And does not it reduce the reusability feature of Java language?
A final class cannot be subclassed. This is done for reasons of security and efficiency. Some of the classes in Java API are final, for example java.lang.System. Sometimes security and immutability is of far more importance than re usability.
According to this IBM developerWorks article :
The common perception is that declaring classes or methods final makes it easier for the compiler to inline method calls, but this perception is incorrect (or at the very least, greatly overstated).
final classes and methods can be a significant inconvenience when programming -- they limit your options for reusing existing code and extending the functionality of existing classes. While sometimes a class is made final for a good reason, such as to enforce immutability, the benefits of using final should outweigh the inconvenience. Performance enhancement is almost always a bad reason to compromise good object-oriented design principles, and when the performance enhancement is small or nonexistent, this is a bad trade-off indeed.
Also read this Open Closed Principle:
Software Entities (Classes, Modules, Functions, etc.) should be open for Extension, but closed for Modification.
final class can not be inherited. So if you want that nobody can inherit your class then you can declare it as final. So you have already answers your own questions. So main usage are
Immutable types
If you dont want someone extend the class.
Both are them are used for security reasons. To protect your system to be changed by using your critical classes. Is not it enough for being a reason?
final keyword can be used with a class in order to provide security. We can take the example of String. String class was made immutable as well as final to enhance security of file handling in java.
Though, performance is also a reason (assuming you are already aware of the internal String pool maintained for making sure that the same String object is used more than once without having to create/re-claim it those many times), but the main reason why String has been made immutable in Java is 'Security'. Surprised? Let's understand why.
Suppose you need to open a secure file which requires the users to authenticate themselves. Let's say there are two users named 'user1' and 'user2' and they have their own password files 'password1' and 'password2', respectively. Obviously 'user2' should not have access to 'password1' file.
As we know the filenames in Java are specified by using Strings. Even if you create a 'File' object, you pass the name of the file as a String only and that String is maintained inside the File object as one of its members.
Had String been mutable, 'user1' could have logged into using his credentials and then somehow could have managed to change the name of his password filename (a String object) from 'password1' to 'password2' before JVM actually places the native OS system call to open the file. This would have allowed 'user1' to open user2's password file. Understandably it would have resulted into a big security flaw in Java. I understand there are so many 'could have's here, but you would certainly agree that it would have opened a door to allow developers messing up the security of many resources either intentionally or un-intentionally.
With Strings being immutable, JVM can be sure that the filename instance member of the corresponding File object would keep pointing to same unchanged "filename" String object. The 'filename' instance member being a 'final' in the File class can anyway not be modified to point to any other String object specifying any other file than the intended one (i.e., the one which was used to create the File object).
More information can be found here Source A
Source B
I research this, and I read this on Hardcore Java, Publisher : O'Reilly ISBN : 0-596-00568-7
Why Classes are tagged Final:
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.
A final class cannot be subclassed. This is necessary to improve security even if it has some drawbacks.
E.g. the class java.lang.String is final. Therefore you cannot subclass String and can be sure that a String parameter is never a subclass that does something harmful (e.g. sending the String somewhere).

Categories

Resources