public interface Proposal {
public static final enum STATUS {
NEW ,
START ,
CONTINUE ,
SENTTOCLIENT
};
}
Java does not allow an enum to be final inside an interface, but by default every data member inside an interface is public static final. Can anybody clarify this?
Java does not allow you to create a class that extends an enum type. Therefore, enums themselves are always final, so using the final keyword is superfluous.
Of course, in a sense, enums are not final because you can define an anonymous subclass for each field inside of the enum descriptor. But it wouldn't make much sense to use the final keyword to prevent those types of descriptions, because people would have to create these subclasses within the same .java file, and anybody with rights to do that could just as easily remove the final keyword. There's no risk of someone extending your enum in some other package.
An enum can't be final, because the compiler will generate subclasses for each enum entry that the programmer has explicitly defined an implementation for.
Moreover, an enum where no instances have their own class body is implicitly final, by JLS section 8.9.
Two things:
enums are final subclasses of java.lang.Enum
if an enum is a member of a class, it is implicitly static
No point in declaring enum final. Final for classes means that they can not be inherited. However, enums can not be inherited by default (that is they are final).
The final thing is valid only for variables. However you should think of the enums more like data types than variables.
Related
This question already has answers here:
Are instances of enums static by default?
(2 answers)
Closed 7 months ago.
I have been recently studying java enums and couldn't understand why they are implicitly public and static by nature. final I understand because they are constants but why the other tags?
If you would look at Java documentation, it is clearly mentioned that:
Programmers can not invoke constructors of enum.
which basically means that we can not create any object of enum using the keyword new. Now if enums weren't static, then how would we access them without any instance/object?
enum Color { RED, GREEN, BLUE; } // enum declaration
Color.RED //accessing enum constant
If you have noticed only have to access enum constants is through enum name (similar to how we access static members of any class).
So to be able to access enum constants without any object we need them to be static.
And enums are by default public so that we can freely access them anywhere however this is not a necessity we can use private or protected modifiers as well.
I have been recently studying Java enums and couldn't understand why they are implicitly public and static by nature.
final I understand because they are constants but why the other tags?
It is complicated, but I think you have some of the facts incorrect there.
According to the Java 17 Language Specification (JLS 8.9)
"It is a compile-time error if an enum declaration has the modifier abstract, final, sealed, or non-sealed."
See below.
"A NESTED enum class is implicitly static. That is, every member enum class and local enum class is static."
And non-nested classes are implicitly static too.
"It is a compile-time error if ... an enum declaration has MORE THAN ONE OF the access modifiers public, protected, and private (§6.6)."
But that is the same as any other class. This doesn't say that it is implicitly public.
"An enum class is either implicitly final OR implicitly sealed ..."
There is something rather subtle going on here. If an enum constant has a class body, then it actually defines an anonymous subclass of the enum class. In this case, the enum class is not final in the sense of "having no subclasses"
So:
Enum classes are NOT implicitly public. They can be private, for example.
Enum classes MAY BE implicitly final in the "has no subclasses" sense. But you were using final in the "constantness" sense. The binding between an enum constant name and the corresponding value cannot change; i.e. it is implicitly final in that sense.
However, the enum values can have mutable fields, so they are not necessarily constant in the sense that 42 is a constant. Just like you can change the array content with the following "constant":
final int[] CONST = new int[]{1, 2, 3};
Enum classes ARE implicitly static in contexts where another class could be non-static.
Why are they implicitly static? Well if they weren't, what would it mean? An implicitly static enum is effectively a set of singleton values. But it it wasn't, then each time you created an instance of the class that enclosed the enum class, you would be creating a new set of enum values. They are no longer singleton. This would be most unexpected ... and I am finding it hard to see how it would be useful.
This code:
interface Config {
int MAX_CONN = 20;
}
compiled and worked as I expected. It looks like this is the same as:
interface Config {
public static final int MAX_CONN = 20;
}
Is "public static final" redundant for a constant in a Java interface? Is this true for Java 1.1, 1.2, 1.3, 1.4,..., 1.8 or did it change in a Java release?
Variables declared in Interface are implicitly public static final. This is what JLS 9.3 says :
Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.
Read through the JLS to get an idea why this was done.
Look at this SO answer:
Interface variables are static because Java interfaces cannot be instantiated in their own right; the value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.
Interface : System requirement service.
In interface, variable are by default assign by public,static,final access modifier. Because :
public : It happen some-times that interface might placed in some other package. So it need to access the variable from anywhere in project.
static : As such incomplete class can not create object. So in project we need to access the variable without object so we can access with the help of
interface_filename.variable_name
final : Suppose one interface implements by many class and all classes try to access and update the interface variable. So it leads to inconsistent of changing data and affect every other class. So it need to declare access modifier with final.
Interface variables are implicitly static and final because Java interfaces cannot be instantiated on their own.
Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations (variable declarations that are declared to be both static and final). An interface may never contain method definitions.
http://en.wikipedia.org/wiki/Interface_(Java)
Interface variables are static because Java interfaces cannot be instantiated in their own right. Value of the variable must be assigned in a static context - no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.
Interface variables are always static and final.
If the interface has to be refactored to a class, it may be more practical to keep the redundant public static final, though. (This sounds odd, because each IDE flags those as redundant information).
EDIT To be fair: One would not do this without changing lots of other places (as interfaces are using implements, while inheriting from classes use extends)
EDIT#2 In fact, constant interface(s) can be considered to be an anti-pattern, please see on wikipedia - Constant Interface
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!
I am just trying to understand why all fields defined in an Interface are implicitly static and final. The idea of keeping fields static makes sense to me as you can't have objects of an interface but why they are final (implicitly)?
Any one knows why Java designers went with making the fields in an interface static and final?
An interface is intended to specify an interaction contract, not implementation details. A developer should be able to use an implementation just by looking at the interface, and not have to look inside the class which implements it.
An interface does not allow you to create an instance of it, because you cannot specify constructors. So it cannot have instance state, although interface fields can define constants, which are implicitly static and final.
You cannot specify method bodies or initializer blocks in an interface, although since Java 8 you can specify default methods with bodies. This feature is intended to allow new methods to be added to existing interfaces without having to update all the implementations. But you still cannot execute such a method, without first creating an instance implementing the interface.
Aside: Note that you can implement an interface with an anonymous inner class:
interface Foo {
String bar();
}
class FooBar {
Foo anonymous = new Foo() {
public String bar() {
return "The Laundromat Café";
};
}
You have to provide the full implementation of the interface for the anonymous inner class to compile.
new Foo() is initializing the anonymous inner class with its default constructor.
Reason for being final
Any implementations can change value of fields if they are not defined as final. Then they would become a part of the implementation. An interface is a pure specification without any implementation.
Reason for being static
If they are static, then they belong to the interface, and not the object, nor the run-time type of the object.
There are a couple of points glossed over here:
Just because fields in an interface are implicitly static final does not mean they must be compile-time constants, or even immutable. You can define e.g.
interface I {
String TOKEN = SomeOtherClass.heavyComputation();
JButton BAD_IDEA = new JButton("hello");
}
(Beware that doing this inside an annotation definition can confuse javac, relating to the fact that the above actually compiles to a static initializer.)
Also, the reason for this restriction is more stylistic than technical, and a lot of people would like to see it be relaxed.
The fields must be static because they can't be abstract (like methods can). Because they can't be abstract, the implementers will not be able to logically provide the different implementation of the fields.
The fields must be final, I think, because the fields may be accessed by many different implementers allows they to be changeable might be problematic (as synchronization). Also to avoid it to be re-implemented (hidden).
Just my thought.
I consider the requirement that the fields be final as unduly restrictive and a mistake by the Java language designers. There are times, e.g. tree handling, when you need to set constants in the implementation which are required to perform operations on an object of the interface type. Selecting a code path on the implementing class is a kludge. The workaround which I use is to define an interface function and implement it by returning a literal:
public interface iMine {
String __ImplementationConstant();
...
}
public class AClass implements iMine {
public String __ImplementationConstant(){
return "AClass value for the Implementation Constant";
}
...
}
public class BClass implements iMine {
public String __ImplementationConstant(){
return "BClass value for the Implementation Constant";
}
...
}
However, it would be simpler, clearer and less prone to aberrant implementation to use this syntax:
public interface iMine {
String __ImplementationConstant;
...
}
public class AClass implements iMine {
public static String __ImplementationConstant =
"AClass value for the Implementation Constant";
...
}
public class BClass implements iMine {
public static String __ImplementationConstant =
"BClass value for the Implementation Constant";
...
}
Specification, contracts... The machine instruction for field access uses object address plus field offset. Since classes can implement many interfaces, there is no way to make non-final interface field to have the same offset in all classes that extend this interface. Therefore different mechanism for field access must be implemented: two memory accesses (get field offset, get field value) instead of one plus maintaining kind of virtual field table (analog of virtual method table). Guess they just didn't want to complicate jvm for functionality that can be easily simulated via existing stuff (methods).
In scala we can have fields in interfaces, though internally they are implemented as I explained above (as methods).
static:
Anything (variable or method) that is static in Java can be invoked as Classname.variablename or Classname.methodname or directly. It is not compulsory to invoke it only by using object name.
In interface, objects cannot be declared and static makes it possible to invoke variables just through class name without the need of object name.
final:
It helps to maintain a constant value for a variable as it can't be overridden in its subclasses.