I was just going through the source code of HashMap in openJDK8 and wanted to understand that although the class TreeMap(static final class TreeNode) is declared as final, there are methods in the class that are declared as final - wanted to understand the significance of that.
since the class is marked as final, the class cannot be extended, and so its methods cannot be over ridden, I have gone through the oracle docs , that says sometimes the methods that are called from constructor needs to be declared as final, but there are some methods that are not called from constructor still they are declared final. So can any one please help me understand.
Below link has complete code:
http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/HashMap.java
final keyword used in method declaration is for different purpose vs final keyword used in class declaration.
final method : -You can declare some or all of a class's methods final. You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this—a number of its methods are final.
final class :- you can also declare an entire class final. A class that is declared final cannot be subclassed. This is particularly useful, for example, when creating an immutable class like the String class.
Source:-https://docs.oracle.com/javase/tutorial/java/IandI/final.html
"final" keyword is used in a method declaration to indicate that the method cannot be overridden by subclasses.
In addition to that, there are some performance advantages of it:
"final methods can be inlined after being loaded into the JVM, because at that point the JVM knows definitely that the method is final. So compilers that operate after class loading, such as JIT compilers, can take advantage of final methods. Consequently, methods declared final could have some performance benefit."
However despite its performance advantage, the most important usage aim is "clear design". It is used in HashMap to indicate those methods will not be overriden by the subclasses since their implementation is guaranteed in that way
Related
Why can I not have a interface inside of a inner class? Why are they inherently static? Sorry if it's a stupid question, I've tried my best to google this again and again but I can't seem to wrap it around my head. As in why cannot I declare these in inner classes/local classes?
Also just as a confirmation, the reason we can have static final variables in a interface is because they do not specify the state or any of that sort of the implementation right? If we lose static and use just a final, we need a instance which makes no sense cause you can't instantiate a interface. Sorry, I really am confused, and I know I should just make another question but I think these two questions are somewhat related.
Think about what static means - "not related to a particular instance". So, as you point out, a static field of class Foo is a field that does not belong to any Foo instance, but rather belongs to the Foo class itself.
Now think about what an interface is - it's a contract, a list of methods that classes which implement it promise to provide. Another way of thinking about this is that an interface is a set of methods that is "not related to a particular class" - any class can implement it, as long as it provides those methods.
So, if an interface is not related to any particular class, clearly one could not be related to an instance of a class - right?
*Note, as #Owlstead points out, there are ways of defining interfaces within classes. But, for the purposes of wrapping your head around what an interface is (which seems to be what you're working on), I would ignore those possibilities for now as they distract from and possibly obscure the purpose of interfaces in general.
Why are they [interfaces] inherently static?
The difference between a static and a non-static nested class is in whether their instances have implicit references to enclosing instances (of the containing class), as well as to local variables from the containing scope. Before Java 8, there was no way for an interface to make use of such implicit references, because an interface could not initialize any non-static fields or provide any method implementations. (It still can't initialize non-static fields, though now it can provide default method implementations.) So before Java 8, there was no meaning in a non-static nested interface.
Also, from an implementation standpoint, these implicit references are implemented as an extra fields on the inner class, and they also require extra arguments to the inner-class constructor (in order to initialize these fields). Interfaces don't have fields, or constructors, so there's no way to implement this.
(Note: I don't usually recommend trying to understand language design decisions in terms of the implementation, because a single language feature can have many different correct implementations. But I think this is one case where understanding the implementation helps to understand the specification, hence the previous paragraph.)
Why can I not have a interface inside of a inner class?
Because interfaces are implicitly static: JLS §8.5.1:
A member interface is implicitly static (§9.1.1). It is permitted for the declaration of a member interface to redundantly specify the static modifier.
and you can't have non-final statics in an inner class.
Why are they implicitly static?
Because that's the way they designed it.
why cannot I declare these in inner classes/local classes?
Because they're implicitly static.
the reason we can have static final variables in a interface is because they do not specify the state or any of that sort of the implementation right?
Right.
If we lose static and use just a final, we need a instance
Right.
which makes no sense cause you can't instantiate a interface.
Yes you can. You can instantiate a class which implements the interface, or you can instantiate a method-local anonymous implementation of it. The real issue here is multiple inheritance of interfaces.
You cannot have an interface inside of an inner class because an inner class only exists within the context of an instance of an 'outer class'. Since this is the case, your interface would be de facto non-static.
You can, however have an interface inside of a nested class. See #owlstead answer. By placing the 'static' keyword on a the declaration of an 'inner class', it becomes a first class citizen, referencable from outside the outer class and (mostly) independent of the context of the outer class. Nested classes can be instantiated outside of the outer class; inner classes cannot.
After Java 16 release we can have static members inside Inner classes and static variables can be declared if they are final or effectively final. See this image
https://docs.oracle.com/en/java/javase/17/language/java-language-changes.html#GUID-8FD2B5E3-46C7-4C6C-8E8A-64AB49ABF855
This question already has answers here:
Make private methods final?
(6 answers)
Closed 8 years ago.
Is there an advantage to declaring a private method as "final" in Java?
If my understanding is correct, the "final" Modifier makes sure I cannot override a method in a subclass and so this may make this method more efficient during runtime. Some literature says it can be inlined if it is final for example which may make the method call faster. Also, the Java runtime won't have to go look for other method in the inheritance hierarchy if it is declared final.
However, private functions cannot be overriden, so are they implicitly "final" as well? Is there a difference between the following two declarations:
private void myFun()
and
private final void myFun();
Subclasses may not override private methods by design. Furthermore, the final keyword tells the compiler that subclasses may not override a method regardless of its access level.
Since private already implies that a subclass may not override a method, declaring a private method to be final is redundant. Making the declaration won't cause problems, but it won't accomplish anything either, since privates are automatically considered final.
All compilers will treat private methods as final. The compiler will not allow any private method to be overridden. Likewise, all compilers will prevent subclasses from overriding final methods.
Update
In your question you're saying
the "final" Modifier makes sure I cannot override a method in a
subclass and so makes this method more efficient during runtime
This is quite a questionable statement. If you declare your private method final, the optimization will depend on the compiler you are using and it's settings. That means NO. No, it's not necessarily true that if you do declare your method private and final, or just final, it would run faster.
No, the final keyword is unnecessary for private methods.
Per definition, there is no difference between private and private final.
For more information, see 'final methods' in the Java Language Specification.
These are the different meanings and advantages of final in Java :
The final keyword on a primitive type variable makes it a constant impossible to reassign. the interest is obvious.
The final keyword on an object variable prevents its reference from being changed.
The final keyword on a method prevents it from being overrided in a subclass. It is useful to protect the functionality of a critical method the superclass while letting the subclasses see it.
The final keyword on a class prevents it from being extended by another class. It is most of the time a bad idea but many base classes of the standard library are like this (for example java.lang.Math, java.lang.String, java.lang.Integer...)
As you can see, declaring some method both private and final is equivalent to declaring it as simply private because in both cases, subclass won't be able to override it.
However, there is a difference for a variable. Indeed, declaring it private will only hide it to other classes whereas adding final will also prevents its reference from being changed in the code of the current class (an will force the constructors to initialize it).
I would like to find out when should you use static, final, static final parameters for variables and (or) methods. As much as I understand:
final: used similar to const parameter in c++. It basically means that value (or in methods - returned value) is not going to change.
static: it means that value (or method) is not assigned directly to some object - therefore you are able to use static variable (or method) in other classes without creating object
final static: does this combination mean that you have variable (or method), which you are able to access without creating object (static) and you are unable to change its value (like in c++ const) (final)
If I am right, than I don't get one thing. In IntelliJ IDE when you declare method as public final static, it points out that final should be removed, because static has already been pointed out. Why, how, when???
static means that a field or method belongs to the class, as opposed to individual instances of the class.
final actually means different things when applied to methods versus fields (or local variables):
final variables and fields cannot be reassigned. This is fairly similar to C++'s const.
final methods cannot be overridden, which only applies to methods on instances. When used in this sense, final is not similar to C++'s const.
Because you cannot override static methods on classes, the combined modifiers static final are usually redundant, which is why IntelliJ advises you to remove one of the modifiers.
Additional notes:
final variables and fields can refer to instances that may change, even though the references themselves cannot change.
Though you didn't ask about classes, final has a third meaning there: final classes cannot be subclassed. static can also be applied to nested classes (classes within classes), but it has the same meaning: A static nested class does not belong to exactly one instance of the enclosing class, which it would otherwise.
Though static methods cannot be overridden, there's a similar behavior called "shadowing" or "method hiding", by which a subclass offers a static method of the same name and signature as the subclass. This behaves differently from overriding, but similarly, static final methods cannot be shadowed.
Related SO question: "Is it a bad idea to declare a final static method?"
So I have looked around google and SO , I cannot find a example or explanation of : What is the purpose of static final methods in enum?
What I understand :
Methods declare static can be accessed like function/procedural languages.
final means you can't override it. Can't change the reference. As assylias pointed out in comments static can't be overridden either.
enums can't be subclassed, explained here.
So what's the point of static final methods in enums if it will never be overridden since there won't be a subclass?
By making a static method final, you prevent it from being hidden (only instance methods can be overriden) by a subclass.
Since enum can't be subclassed, making a static method final is superfluous but not forbidden.
Note: technically, each enum constant that has a class body implicitly defines an anonymous class that extends the enum. But since inner classes may not declare static methods, the static final method could not be hidden in such a constant's class body.
It's easy to see why static methods make sense, so I guess the question is about the final modifier.
final serves no purpose here, except maybe make the code a bit easier to read, but not by much.
It's similar to the way interface methods are often written as public void foo();, even though interface members are always public anyway.
In Java Enum types are used to represent fixed set of constants and making it static final helps its initialisation only once, single copy to be shared across all instances, accessing the variable with the class name and with final its more like a read-only
When you declare instances of an enum you can override the enum's methods, essentially enum instances are implemented as (or thought of) as subclasses. static methods can't be overridden in any case but the implication in the OP and other answers that final is superfluous for an enum is false.
Why can't constructors be final, static, or abstract in Java?
For instance, can you explain to me why this is not valid?
public class K {
abstract public K() {
// ...
}
}
When you set a method as final it means: "I don't want any class override it." But according to the Java Language Specification:
JLS 8.8 - "Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding."
When you set a method as abstract it means: "This method doesn't have a body and it should be implemented in a child class." But the constructor is called implicitly when the new keyword is used so it can't lack a body.
When you set a method as static it means: "This method belongs to the class, not a particular object." But the constructor is implicitly called to initialize an object, so there is no purpose in having a static constructor.
The question really is why you want constructor to be static or abstract or final.
Constructors aren't inherited so can't be overridden so whats the use
to have final constructor
Constructor is called automatically when an instance of the class is
created, it has access to instance fields of the class. What will be
the use of a static constructor.
Constructor can't be overridden so what will you do with an abstract
constructor.
A Java constructor is implicitly final, the static / non-static aspects of its semantics are implicit1, and it is meaningless for a Java constructor to be abstract.
This means that the final and static modifiers would be redundant, and the abstract keyword would have no meaning at all.
Naturally, the Java designers didn't see in any point in allowing redundant and/or meaningless access modifiers on constructors ... so these are not allowed by the Java grammar.
Aside: It is a shame that they didn't make the same design call for interface methods where the public and abstract modifiers are also redundant, but allowed anyway. Perhaps there is some (ancient) historical reason for this. But either way, it cannot be fixed without rendering (probably) millions of existing Java programs uncompilable.
1 - Actually, constructors have a mixture of static and non-static semantics. You can't "call" a constructor on an instance, and it they are not inherited, or overridable. This is similar to the way static methods work. On the other hand, the body of a constructor can refer to this, and call instance methods ... like an instance method. And then there is constructor chaining, which is unique to constructors. But the real point is that these semantics are fixed, and there is no point allowing a redundant and probably confusing static modifier.
public constructor: Objects can be created anywhere.
default constructor: Objects can be created only in the same package.
protected constructor: Objects can be created by classes outside the package only if it's a subclass.
private constructor: Object can only be created inside the class (e.g., when implementing a singleton).
The static, final and abstract keywords are not meaningful for a constructor because:
static members belong to a class, but the constructor is needed to create an object.
An abstract class is a partially implemented class, which contains abstract methods to be implemented in child class.
final restricts modification: variables become constant, methods can't be overridden, and classes can't be inherited.
Final: Because you can't overwrite/extend a constructor anyway. You can extend a class (to prevent that you make it final) or overwrite a method (to prevent that you make it final), but there is nothing like this for constructors.
Static: If you look at the execution a constructor is not static (it can access instance fields), if you look at the caller side it is (kind of) static (you call it without having an instance. Its hard to imagine a constructor being completely static or not static and without having a semantic separation between those two things it doesn't make sense to distinguish them with a modifier.
Abstract: Abstract makes only sense in the presence of overwriting/extension, so the same argument as for 'final' applies
No Constructors can NEVER be declared as final. Your compiler will always give an error of the type "modifier final not allowed"
Final, when applied to methods, means that the method cannot be overridden in a subclass.
Constructors are NOT ordinary methods. (different rules apply)
Additionally, Constructors are NEVER inherited. So there is NO SENSE in declaring it final.
Constructors are NOT ordinary methods. (different rules apply)
Additionally, Constructors are NEVER inherited. So there is NO SENSE in declaring it final.
No Constructors can NEVER be declared final. YOur compiler will always give an error of the type "modifer final not allowed"
Check the JLS Section 8.8.3 (The JLS & API docs should be some of your primary sources of information).
JLS section 8 mentions this.
Constructors (§8.8) are similar to methods, but cannot be invoked
directly by a method call; they are used to initialize new class
instances. Like methods, they may be overloaded (§8.8.8).
But constructors per say are not regular methods. They can't be compared as such.
why constructor can not be static and final are well defined in above answers.
Abstract: "Abstract" means no implementation . and it can only be implemented via inheritance. So when we extends some class, all of parent class members are inherited in sub-class(child class) except "Constructor". So, lets suppose, you some how manage to declare constructor "Abstract", than how can you give its implementation in sub class, when constructor does not get inherit in child-class?
that's why constructor can't be
abstract .
lets see first
final public K(){
*above the modifier final is restrict 'cause if it final then some situation where in some other class or same class only we will override it so thats not gonna happen here proximately not final
eg:
we want public void(int i,String name){
//this code not allowed
let static,, static itz all about class level but we create the object based constructor by using 'new' keyword so,,,,,, thatsall
abstract itz worst about here not at 'cause not have any abstract method or any declared method
Unfortunately in PHP the compiler does not raise any issue for both abstract and final constructor.
<?php
abstract class AbstractClass
{
public abstract function __construct();
}
class NormalClass
{
public final function __construct() {
echo "Final constructor in a normal class!";
}
}
In PHP static constructor is not allowed and will raise fatal exception.
Here in AbstractClass obviously a constructor either can be declared as abstract plus not implemented or it can be declared as something among (final, public, private, protected) plus a function body.
Some other related facts on PHP:
In PHP having multiple constructor __construct() is not possible.
In PHP a constructor __construct() can be declared as abstract, final, public, private and protected!
This code was tested and stood true for in PHP versions from 5.6 up to 7.4!