What are the implicit specifier/modifiers of interface methods in Java 8? - java

I understand that Interface methods are implicitly public. Java Docs Tutorial says
All abstract, default, and static methods in an interface are
implicitly public, so you can omit the public modifier.
Out of abstract, static and default, which modifiers are implicitly declared in Java 8.
I thought abstract was not implicitly declared anymore as Java 8 introduced default method in interfaces, but I still get a warning in Intellij IDEA.
Modifier 'abstract' is redundant for interface methods.
public interface TestInterface {
abstract int print(); // abstract redundant ?.
int print2(); //legal.but public or public abstract ?.
}

The language spec - specifically Section 9.4, states that abstract and public are implicit.
Every method declaration in the body of an interface is implicitly public (§6.6). It is permitted, but discouraged as a matter of style, to redundantly specify the public modifier for a method declaration in an interface.
An interface method lacking a default modifier or a static modifier is implicitly abstract, so its body is represented by a semicolon, not a block. It is permitted, but discouraged as a matter of style, to redundantly specify the abstract modifier for such a method declaration.
This is why IntelliJ warns you about it; by the JLS, you're doing something completely redundant.
As a bonus, fields in interfaces are implicitly public static final:
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.

In Java 7, as well in Java 8, all fields defined in an interface are ALWAYS public, static, and final. Methods are public and abstract.
Because your print() method does not have a body, it means that is an abstract method. With other words does not need to be declared explicitly abstract, that's why Intellij IDEA says is redundant.
Methods without static or default are not implicitly abstract, even if it has a body. A non-abstract method with a body that is not default or static, cannot exist in an interface.

Access modifiers
In Java 8, we have as per Java Docs Tutorials,
All abstract, default, and static methods in an interface are
implicitly public, so you can omit the public modifier.
Thus the only allowed access modifier in an Interface as of Java 8 is public. (Java 9 introduces private interface methods)
public interface TestInterface {
int print();//compiles and no IDE warning
public int print1();//public redundant
}
Optional Specifiers
abstract - methods in an interface that are not declared as default or static are implicitly abstract, so the abstract modifier is optional. But the method implementation must not be provided in such case.
static- static needs to be explicitly specified and implementation provided.
final - A final methods can't be overridden and is not allowed for an interface method.
default - method can be explicitly declared default if the default implementation is provided.
All fields in Interfaces are public, static and final.

Related

Is it unnecessary to specify public or public abstract in the code below? [duplicate]

This question already has answers here:
Java abstract interface
(9 answers)
Should methods in a Java interface be declared with or without a public access modifier?
(12 answers)
Closed 2 years ago.
interface Airplane {
String fuelOption = "kerosene";
public abstract String getFuelOption();
}
Is it necessary to specify public or public abstract in the line with the getFuelOption() method?
Thank you!
The public access modifier is not needed because
Every method declaration in the body of an interface is implicitly
public (§6.6). It is permitted, but discouraged as a matter of style,
to redundantly specify the public modifier for a method declaration in
an interface. (Section 9.4)
The abstract access modifier is not needed because
A default method is a method that is declared in an interface with the
default modifier; its body is always represented by a block.
And...
An interface method lacking a default modifier or a static modifier is implicitly abstract, so its body is represented by a semicolon, not a block.
Given that default methods have a body, and those that don't are inherently abstract, and every method declaration on an interface is inherently public, you don't need to specify either keyword.
Please refer below JLS :
https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#:~:text=Every%20method%20declaration%20in%20the,method%20declaration%20in%20an%20interface.&text=Default%20methods%20are%20distinct%20from,which%20are%20declared%20in%20classes.
No, All interface methods are public and abstract by default.
relevant text from the Java language spec, Section 9.4
A method in the body of an interface may be declared public or private .If no access modifier is given, the method is implicitly
public.
An interface method lacking a private, default, or static modifier is
implicitly abstract. Its body is represented by a semicolon, not a
block.

Java 9 Interface : Why default Modifier Converted into public Modifier

My Question is about interface. I create an interface and define four methods: first method is a private method; second is a default method; third is a static method; and fourth is an abstract method.
After compiling this interface and checking its profile: the default method is converted into a public method, and both the static and abstract methods have a prepended public modifier. Why is this?
Code:
interface InterfaceProfile {
private void privateM() { //this method is hidden
System.out.println("private Method");
}
default void defaultM() {
System.out.println("Default Method");
}
static void staticM() {
System.out.println("Static Method");
}
void doStuff(); //by default adds the public modifier
}
InterfaceProfile class
D:\Linux\IDE\Workspace\OCA-Wrokspace\Ocaexam\src>javap mods\com\doubt\session\InterfaceProfile.class
Compiled from "InterfaceProfile.java"
interface com.doubt.session.InterfaceProfile {
public void defaultM();
public static void staticM();
public abstract void doStuff();
}
The fact that it's a default method doesn't make a difference. The implicit scope is public.
Here's what the tutorial says:
All abstract, default, and static methods in an interface are implicitly public, so you can omit the public modifier.
Simple: by default, all methods in an interface are public. You can restrict that by applying private, but whenever you do not do that, that default kicks in. Thus: there is no conversion taking place at all.
Quoting the Java Language Specification:
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.
( the ability to have private methods in interfaces was introduced with Java 9, as people discovered that Java 8 default methods often created the need to have, well, private methods that such default methods could make use of, without making these helper methods publicly visible )
The default modifier is public, because that is how the interface declaration is defined:
https://docs.oracle.com/javase/tutorial/java/IandI/interfaceDef.html
If you are asking for the reasoning behind this, i would argue that the purpose of defining an interface is to ensure the - well - interface of all implementing classes, meaning that all implementing classes have clear contracts on which public accessable methods they need to provide.
Adding private methods to an interface does not serve this primary purpose and seems to be more of an implementation hint. Private and abstract methods were late additions to interfaces.
Related: Should methods in a Java interface be declared with or without a public access modifier?
https://docs.oracle.com/javase/tutorial/java/IandI/interfaceDef.html
All abstract, default, and static methods in an interface are implicitly public, so you can omit the public modifier.
In effect, a class that implements an interface exposes all of the interface methods (other than private) to any other code that has visibility of the class.
It would be very confusing if a class had an interface but the methods on the interface would be visible to some code and not other. If you want to selectively expose methods, then you should probably make use of multiple interfaces.
public interface Profile {
generalMethod() ...
}
public interface SecretProfile extends Profile {
secretMethod() ...
}
Classes may choose to implement either of the interfaces (or even both). 3rd party code can check for the presence of the interface and know that the method is available or not.

What's is the difference between a static and non-static annotation?

Java's inner classes can be static or non-static. Non-static inner classes are tied to an instance of the enclosing class.
Annotations are a type of Java interface, and like any other class, they can be defined inside a class. Similarly, they can be declared static or non-static. What is the difference between these two choices, is there any difference between how they're used by consuming code, and is there any scenario where it'd make sense to use one or the other?
Example:
public class AnnotationContainer {
public static #interface StaticAnnotation {}
public #interface NonstaticAnnotation {}
}
No difference at all. Nested interfaces are always static.
This is described in JLS Sec 8.5.1 (for classes):
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 JLS Sec 9.5 (for interfaces):
A member type declaration in an interface is implicitly public and static. It is permitted to redundantly specify either or both of these modifiers.
To expand a bit on Andy's correct answer that they are exactly the same because they are a special kind of interface declaration and "member interfaces" are implicitly static anyway:
JLS 10 9.6. Annotation Types:
An annotation type declaration specifies a new annotation type, a special kind of interface type. To distinguish an annotation type declaration from a normal interface declaration, the keyword interface is preceded by an at-sign (#).
JLS 10 8.5.1. Static Member Type Declarations :
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 JLS 10 9.1.1. Interface Modifiers
The modifier static pertains only to member interfaces (§8.5.1, §9.5), not to top level interfaces (§7.6).
Side note: interestingly, these Chapters do not use the term "nested interface" defined at the top of Chapter 9, but it seems to be a synonym for "member interface":
JLS 10 Chapter 9. Interfaces:
A nested interface is any interface whose declaration occurs within the body of another class or interface.

Why can't constructors be final, static, or abstract?

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!

Methods visibility in interface

Do all methods in an Interface has by default Public visibility mode?
All methods in an interface default to public.
See Java Language Specification 6.6.1 which states
All members of interfaces are
implicitly public.
All interface methods ARE public abstract, all interface fields are public static final...
see here.
Just to add to other answers here: all methods are public, however, if the interface itself is package-local then effectively all methods are also package-local.
You can therefore mix public and package-local methods, by making a package-local interface extend a public one.
public interface P{
void iAmPublic();
}
interface L extends P{
void iAmPackageLocal();
}
Here L effectively has one public and one package-local method. Clients from outside the package will only see iAmPublic(), whereas ones from inside the package will see both methods.
In the same way you can nest interfaces inside other classes to achieve even tighter method visibility.
Yes, all methods of an interface are public, and can't have any other access modifier (i.e. the default public access modifier is the only valid access modifier)
Yes, all methods in an interface are implicitly public and abstract.
Check Java language specification chapter 9.4

Categories