I am a java beginner trying to learn some java.
Often, I'm always confused between Static and final keywords in java. Although they sound similar. How are they different?
Can anyone explain?
Sorry for basic question. I'm just trying to learn!
EDIT: I've tried to lookup various sites and they often confuse me. Can anyone help me out?
(PS: Please don't curse me for asking basic question)
Lets look at static variables and static methods first.
superkeywords in anyway
Java also has "static nested classes",A static nested class is just one which doesn't implicitly have a reference to an instance of the outer class.
Static nested classes can have instance methods and static methods.
There's no such thing as a top-level static class in Java.
main method is
staticsince it must be be accessible for an application to run before any instantiation takes place.
finalkeyword is used in several different contexts to define an entity which cannot later be changed.
final class cannot be subclassed. This is done for reasons of security and efficiency. Accordingly, many of the Java standard library classes are
final, for example
java.lang.String. All methods in a
final class are implicitly
final method can't be overridden 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.
final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a
blank final variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared; otherwise, a compile-time error occurs in both cases.
When an anonymous inner class is defined within the body of a method, all variables declared
final in the scope of that method are accessible from within the inner class. Once it has been assigned, the value of the final variable cannot change.