Java 9 allows us to have private methods in interface, which means that not explicitly marking public methods is no longer superfluous.
However, is it now mandatory to do so? I hope the specification still assumes public abstract as the default modifier for methods to maintain backward compatibility with earlier source code?
The Java 9 Language Specification says in §9.4::
A method in the body of an interface may be declared public or private (§6.6). If no access modifier is given, the method is implicitly public. It is permitted, but discouraged as a matter of style, to redundantly specify the public modifier for a method declaration in an interface.
Unfortunately, I can't find a link that does not lead to a PDF, diffing the old and new JLS.
What I was taught:
All members in an Interface are implicitly public and cannot be declared
with any other access modifier, unless specified below:
Fields & all variables are public static final implicitly
method signatures, default methods, (permitted as of Java 8) declared with the 'default' modifier.
Static methods (permitted as of Java 8)
Private methods (permitted as of Java 9) both static and non-static concrete methods can be private.
Nested types.
Method bodies exist only for default, private and static methods.
Source: Tim Buschalka's Learn Programming Academy
Also a very clear but somewhat long explanation: https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html
Related
This question already has answers here:
Are static methods inherited in Java?
(15 answers)
Are static variables inherited
(4 answers)
Closed 4 years ago.
If static members are not inherited in Java then why access modifiers (private, protected…) are applicable to them?
Perhaps, I’m not 100% clear on the term “inherited”:
when they say “statics not inherited” do they mean “not visible” or “can not be redefined/reimplemented” or both?
Would it be correct to say that access modifiers imply only visibility when speaking about static class members, and visibility as well as reimplementation possibility when speaking about regular class members?
Can you please provide examples when making static, say, private makes sense?
Thanks
PS: Now I think that the statement "Static variables in Java are not inherited, they exist only in the class which declares them" spread here and there and around on this forum (for instance: What are the rules dictating the inheritance of static variables in Java?) IS NOT correct as
The Java Language Specification #8.4.8 states:
8.4.8 Inheritance, Overriding, and Hiding
A class C inherits from its direct superclass all concrete methods m (both static and instance) of the superclass for which all of the following are true:
m is a member of the direct superclass of C.
m is public, protected, or declared with package access in the same package as C.
No method declared in C has a signature that is a subsignature (§8.4.2) of the signature of m.
If static members are not inherited in Java then why access modifiers
(private, protected…) are applicable to them?
Who said that static members cannot be inhertied, refer following JLS (§Example 8.2-2). example
In Java being "static" simply means that there is no object required to access this field/method.
"private" is just an access modifier which means that following field/method cannot be accessed outside of its, and can only accessed by this class itself or any inner class.
Only thing with "static" methods of a superclass inherited in subclass can be read understood from below excerpt from JLS:
If a class C declares or inherits a static method m, then m is said to
hide any method m', where the signature of m is a subsignature
(§8.4.2) of the signature of m', in the superclasses and
superinterfaces of C that would otherwise be accessible to code in C.
So, basically you cannot override a static method but you can certainly inherit a static method, if it is not hidden by subclass.
Read following JLS section (§8.4.8.2. Hiding (by Class Methods)) about hiding of class methods.
Also, you can read Java's inheritance tutorial from here and below is a screen shot of summary from same page
Member visibility doesn't just apply to child classes. From Oracle, they apply, in reference to a static member, to the rest of the package, or the rest of the "world".
If you create a private static member, you're stating that this is a member exclusive to that specific class. You then work your way up the visibility chain:
private is least visible,
<no modifier> (or package-protected) is second-least visible,
protected is second-most visible, and
public is most visible.
I've not seen anyone really use a protected static member, even though it's valid Java. Convention dictates that this should be a visible constant (in that case it's likely public), or a less-than visible constant for test exposure (which would justify package-protected visibility.
A static member in a class simply means that it will be shared across all the objects of the class. A new variable won't be instantiated for every instance of the class.
Access modifiers control the visibility of variables in Java. The meaning of the access modifiers is the same for static as well as non-static members. It has nothing to do with static members only.
With respect to your question, the use of access modifiers in static variables means the following:
private static count: The static member count is only visible to the class defining it. However, if you inherit the class defining this static variable, your inherited class cannot directly access it. count can be accessed only if super class has a getter defined for it, or if the access modifier is changed to public or protected.
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've been wondering why it's allowed to do a code implementation in an interface, when interfaces are suppossed to contain no code implementation:
public interface someInterface{
String someString = "example";
}
I can make a class implement this interface, without getting an error:
public class someClass implements someInterface
How come?
You are allowed to declare constants in interfaces, which is what you have done. You have not implemented code.
Variables declared in interfaces are implicitly declared public static final.
The JLS, Section 9.3, covers this:
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.
According to java docs
Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.
Here you are not defined any methods to implement.So you didn't get any error here.
There is no strict condition that an interface must have signatured methods.Remember there are Marker Interfaces too in java.
And secondly , You can declare variables inside interface.
And that variable someString assigned in a static context and shared across all the implemntations by that interface
Point is that the variables inside declared interface are implicitly static and final.You can use them.
I was reading this post Why would a static nested interface be used in Java? in particular the first answer. In that answer is written that use the words "public" or "public final" on interface fields are redundant. My question is: why?
Why should I remove them? If I have something like this:
public interface Int1 {
public void add();
void remove();
}
Doesn't it mean that I want add method to be implementated by whatever class while remove method to be implementated only by classes of my same package?
Are “public” and “public final” redundant for interface methods?
Yes.
All methods in an interface are implicitly public and abstract (but not final).
All fields in an interface are implicitly public, static and final.
The JLS states this. It also states that these modifiers can be left out.
Why? Well there are a variety of reasons:
Fields and methods are implicitly public because the point of an interface is to declare an ... interface that other classes can see. (If you want / need to restrict access, this is done via an access modifier on the interface itself.)
Fields are static because if they were not you would be declaring visible instance fields on an object ... and that's bad for encapsulation.
Fields are final because non-final fields would be another way of declaring public static fields ... which are terrible from an OO perspective.
Methods are abstract because allowing method bodies would effectively turn interfaces into abstract classes.
Another reason for making methods abstract and fields static in an interface is that if they didn't, diamond inheritance, and inheritance of a method from two distinct interfaces would both be problematic.
But either way, this is how Java is defined, so the questions are moot ... unless you are thinking of inventing your own programming language.
Note that in Java 8, you can declare methods in an interface, using the default modifier. And in Java 9, you can declare private methods, in some cases. But use of the public keyword is still redundant.
Why should I remove them?
You don't have to remove them. The Java compiler doesn't care.
You can remove them, but you don't have to remove them, unless you are trying to conform to some Java style guidelines that insist on this.
Your code will probably be more readable if you are consistent, but you could make it consistent by using the redundant modifiers everywhere; e.g. adding them rather than removing them.
Doesn't it mean that I want add method be implemented by whatever class while remove method implemented only by classes of my same package?
No it doesn't mean that. Or at least, it might mean that to you, but it won't mean that to the Java compiler, other Java tools ... or other people reading and maintaining your code. IMO, it would be ill-advised to place any meaning on the presence or absence of redundant keywords.
You cannot have a final method declared in an interface. Fields are always final but methods are always abstract (and never final). You cannot define an interface method that is to be implemented only by classes in the same package.* From section 9.3 of the Java Language Specification:
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.
and from section 9.4:
Every method declaration in the body of an interface is implicitly public (§6.6).
Every method declaration in the body of an interface is implicitly abstract, so its body is always represented by a semicolon, not a block.
It is permitted, but discouraged as a matter of style, to redundantly specify the public and/or abstract modifier for a method declared in an interface.
* As Paul Bellora points out in a comment, you can make the interface itself package-private (or protected, or even private) if you want to restrict its visibility.
Interfaces by definition are abstract so the abstract modifier on the interface is redundant.
Variables in interfaces and annotations are automatically public, static and final, so these modifiers are redundant as well.
As annotations are a form of interface, their fields are also automatically public, static and final just as their annotation fields are automatically public and abstract.
Final classes by definition cannot be extended so the final modifier on the method of a final class is redundant.
reading this: http://checkstyle.sourceforge.net/config_modifier.html
Yes the public is redundant, because in an Interface all methods are implictly public and abstract.
I think its is a bad style to add public, or abstract, because both are implicitly applied.
public interface Int1 {
void add();
void remove();
}
This looks cleaner, and shows that you know, that they are implict public
from Java Language Specification (JLS)
9.4. Abstract Method Declarations
Every method declaration in the body of an interface is implicitly public (§6.6).
Every method declaration in the body of an interface is implicitly
abstract, so its body is always represented by a semicolon, not a
block.
It is permitted, but discouraged as a matter of style, to redundantly
specify the public and/or abstract modifier for a method declared in
an interface.
I write interfaces without the public keyword for methods. It's redundant.
In java document, it is said :
Unlike interfaces, abstract classes
can contain fields that are not
static and final, and they can contain
implemented methods.
Is that a correct text? that not part confuses me because interfaces don't have static or final fields, right?
Source : http://download.oracle.com/javase/tutorial/java/IandI/abstract.html
Thanks.
Edit :
public interface GroupedInterface extends Interface1,
Interface2, Interface3 {
// constant declarations
double E = 2.718282; // base of natural logarithms
// method signatures
void doSomething (int i, double x);
int doSomethingElse(String s);
}
An interface can contain constant
declarations in addition to method
declarations. All constant values
defined in an interface are implicitly
public, static, and final. Once again,
these modifiers can be omitted.
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.
from section 9.3 of the Java Language Specification (here)
Click on "Defining an Interface" on the link in your question:
An interface can contain constant
declarations in addition to method
declarations. All constant values
defined in an interface are implicitly
public, static, and final. Once again,
these modifiers can be omitted.
That is the correct text.
All fields in an interface are inferred to be public, static and final, whether or not explicitly so declared. Just as all methods are public and abstract, whether or not so declared.
the think is.. all fields inside an interface will be static and final, even if you didnt write the static and final!
The documentation is correct. Interfaces may contain static final fields to be used as constants. Abstract classes may contain instance variables to be inherited by extending classes. Those variables are then available in instances of the extending classes.
The quote is correct. Interfaces can have static final fields, but cannot have any other combination (non-static or non-final).
Fields on an interface are static and final by default, adding the modifiers is not necessary because there's no alternative.
For an abstract class it can make sense to give it mutable state, see java.util.AbstractList. Interfaces are not allowed to have any member that would confer mutable state on a class implementing it.