You cannot declare an interface inside a block like below
public void greetInEnglish() {
interface HelloThere {
public void greet();
}
class EnglishHelloThere implements HelloThere {
public void greet() {
System.out.println("Hello " + name);
}
}
HelloThere myGreeting = new EnglishHelloThere();
myGreeting.greet();
}
In This Oracle tutorial I got "You cannot declare member interfaces in a local class." because "interfaces are inherently static."
I am eagar to understand this with more rational information, why and how interface are inherently static?
and why above code does not make sense?
Thanks in advance to elloborate!
I am eagar to understand this with more rational information, why and
how interface are inherently static?
because interfaces are implicitly static, 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.
and why above code does not make sense?
because of the above reason ,
Now lets make it simple :
What static means - "not related to a particular instance". So, suppose, 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?
I also suggest you to study Why static can't be local in Java?
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.
If they are static, then they belong to the interface, and not the object, nor the run-time type of the object.
An interface provide a way for the client to interact with the object. If variables were not public, the clients would not have access to them.
Your code does not make sense because you define the interface within the body of a method. You can define an interface either at top level or in another class or interface.
You cannot declare an interface inside a block
reference
Related
I have just found a static nested interface in our code-base.
class Foo {
public static interface Bar {
/* snip */
}
/* snip */
}
I have never seen this before. The original developer is out of reach. Therefore I have to ask SO:
What are the semantics behind a static interface? What would change, if I remove the static? Why would anyone do this?
The static keyword in the above example is redundant (a nested interface is automatically "static") and can be removed with no effect on semantics; I would recommend it be removed. The same goes for "public" on interface methods and "public final" on interface fields - the modifiers are redundant and just add clutter to the source code.
Either way, the developer is simply declaring an interface named Foo.Bar. There is no further association with the enclosing class, except that code which cannot access Foo will not be able to access Foo.Bar either. (From source code - bytecode or reflection can access Foo.Bar even if Foo is package-private!)
It is acceptable style to create a nested interface this way if you expect it to be used only from the outer class, so that you do not create a new top-level name. For example:
public class Foo {
public interface Bar {
void callback();
}
public static void registerCallback(Bar bar) {...}
}
// ...elsewhere...
Foo.registerCallback(new Foo.Bar() {
public void callback() {...}
});
The question has been answered, but one good reason to use a nested interface is if its function is directly related to the class it is in. A good example of this is a Listener. If you had a class Foo and you wanted other classes to be able to listen for events on it, you could declare an interface named FooListener, which is ok, but it would probably be more clear to declare a nested interface and have those other classes implement Foo.Listener (a nested class Foo.Event isn't bad along with this).
Member interfaces are implicitly static. The static modifier in your example can be removed without changing the semantics of the code. See also the the Java Language Specification 8.5.1. Static Member Type Declarations
An inner interface has to be static in order to be accessed. The interface isn't associated with instances of the class, but with the class itself, so it would be accessed with Foo.Bar, like so:
public class Baz implements Foo.Bar {
...
}
In most ways, this isn't different from a static inner class.
Jesse's answer is close, but I think that there is a better code to demonstrate why an inner interface may be useful. Look at the code below before you read on. Can you find why the inner interface is useful? The answer is that class DoSomethingAlready can be instantiated with any class that implements A and C; not just the concrete class Zoo. Of course, this can be achieved even if AC is not inner, but imagine concatenating longer names (not just A and C), and doing this for other combinations (say, A and B, C and B, etc.) and you easily see how things go out of control. Not to mention that people reviewing your source tree will be overwhelmed by interfaces that are meaningful only in one class.So to summarize, an inner interface enables the construction of custom types and improves their encapsulation.
class ConcreteA implements A {
:
}
class ConcreteB implements B {
:
}
class ConcreteC implements C {
:
}
class Zoo implements A, C {
:
}
class DoSomethingAlready {
interface AC extends A, C { }
private final AC ac;
DoSomethingAlready(AC ac) {
this.ac = ac;
}
}
To answer your question very directly, look at Map.Entry.
Map.Entry
also this may be useful
Static Nested Inerfaces blog Entry
Typically I see static inner classes. Static inner classes cannot reference the containing classes wherease non-static classes can. Unless you're running into some package collisions (there already is an interface called Bar in the same package as Foo) I think I'd make it it's own file. It could also be a design decision to enforce the logical connection between Foo and Bar. Perhaps the author intended Bar to only be used with Foo (though a static inner interface won't enforce this, just a logical connection)
If you will change class Foo into interface Foo the "public" keyword in the above example will be also redundant as well because
interface defined inside another interface will implicitly public
static.
In 1998, Philip Wadler suggested a difference between static interfaces and non-static interfaces.
So far as I can see, the only difference in making an
interface non-static is that it can now include non-static inner
classes; so the change would not render invalid any existing Java
programs.
For example, he proposed a solution to the Expression Problem, which is the mismatch between expression as "how much can your language express" on the one hand and expression as "the terms you are trying to represent in your language" on the other hand.
An example of the difference between static and non-static nested interfaces can be seen in his sample code:
// This code does NOT compile
class LangF<This extends LangF<This>> {
interface Visitor<R> {
public R forNum(int n);
}
interface Exp {
// since Exp is non-static, it can refer to the type bound to This
public <R> R visit(This.Visitor<R> v);
}
}
His suggestion never made it in Java 1.5.0. Hence, all other answers are correct: there is no difference to static and non-static nested interfaces.
In Java, the static interface/class allows the interface/class to be used like a top-level class, that is, it can be declared by other classes. So, you can do:
class Bob
{
void FuncA ()
{
Foo.Bar foobar;
}
}
Without the static, the above would fail to compile. The advantage to this is that you don't need a new source file just to declare the interface. It also visually associates the interface Bar to the class Foo since you have to write Foo.Bar and implies that the Foo class does something with instances of Foo.Bar.
A description of class types in Java.
Static means that any class part of the package(project) can acces it without using a pointer. This can be usefull or hindering depending on the situation.
The perfect example of the usefullnes of "static" methods is the Math class. All methods in Math are static. This means you don't have to go out of your way, make a new instance, declare variables and store them in even more variables, you can just enter your data and get a result.
Static isn't always that usefull. If you're doing case-comparison for instance, you might want to store data in several different ways. You can't create three static methods with identical signatures. You need 3 different instances, non-static, and then you can and compare, caus if it's static, the data won't change along with the input.
Static methods are good for one-time returns and quick calculations or easy obtained data.
In Java Interface, we can have only final variables possible. We can also create static variables in Interface. But, at the same time we are not able to create static/final methods as Interface are only meant for Static Methods.
What is exactly the reason for not allowing static/final methods in Interface ?
A final method can't be overridden. That defies the purpose of having an interface if you cannot actually implement the method.
For the static part, see this question.
You got it wrong.
All variables are implicitly public static and final in interfaces.
Prior to Java 8, you can't create static methods in interfaces. All methods are instance methods.
Since the only goal of an interface is to have classes implementing them, and since methods in interfaces can't have any implementation, making them final would make no sense: they would have no implementation, and could not be overridden.
Interfaces are defined for instances, not statics.
"final" means "can't be overridden". That makes no sense for an interface whatsoever.
final means that it cannot be overriden.
static means that it can only be called using the class name. Since an interface will have multiple implementations, how will you know which implementation to choose since the interface cannot implement the method itself?
Because they are there in an interface to be implemented by some class. What would be the point of a method that can not have an implementation anywhere? (which is what final would suggest)
I have one more point to prove why interface methods can not be static :
interface MyInterface {
static void myStaticMethod();
}
Now let's have two classes are implementing "MyInterface"
// first class
class MyClass1 implements MyInterface {
static void myStaticMethod(){
// some implementation
}
}
// second class
class MyClass2 implements MyInterface {
static void myStaticMethod(){
// some implementation
}
}
Now I am instantiating like below:
1- MyInterface myObj1 = new MyClass1();
2- myObj1.myStaticMethod();
3- MyInterface myObj2 = new MyClass2();
4- myObj2.myStaticMethod();
// here at line 2 & 4 , it's wrong calling as myStaticMethod should be called using class name(because myStaticMethod is defined as static) like below:
MyInterface.myStaticMethod();--> But in this case,how to call different implementations of myStaticMethod() by MyClass1 & MyClass2 classes.
So it's proved that static can not be possible in interface method declaration.
For final ,it's quite clear that it will opposite to override functionality.
An interface is a pure abstract class. Hence, all methods in an interface are abtract, and must be implemented in the child classes. So, by extension, none of them can be declared as final.
Why Interface methods cannot be “static” & “final”?
All methods in an interface are explicitly abstract and hence you cannot define them as static or final because static or final methods cannot be abstract.
In the context of Java 8 and default methods, this question has a new meaning. static methods are now allowed, and why final methods still aren't possible is explained in this question.
1: we can't declare a final method ,because it contradicts it's rule as final method can't be override,but always need to define all the interface methods in it implemented classes.
2: we can't declare a static method ,because it contradicts it's rule as static method always needs the method body but we cant define any method inside a interface.
Well static methods work on classes and not instances so kind of strange/pointless. Having said that I've for one reason or another wanted this in some situations, though can't remember a case now so must have been long ago.
You can "work around" this though (rather alternative api design) as interfaces allow you to declare classes, so something like this:
interface MyInterface {
static class Helpers {
static void myStaticMethod(); //can be abstract etc as usual
}
}
You can subclass that class etc as normal of course, as well make it abstract, abstract methods etc etc.
We can not declare method of interface as static because method of interface instance method and we can not declare final because it is necessory to override method of interface in implemented class. for description check this link enter link description here
By default all the methods present inside an interface are public and abstract. If you declair a method as final inside an interface 1st of all you will get a compiler error and not even then it doesn't make any sense to have a final method because you will never be in a position to override it in child class.
In case of static even if Java allow in what so ever version it's not a good programming practice to use static inside an interface because for static methods u must have to provide the implementation which you must not provide inside an interface. Moreover, even if you provide the implementation inside an interface still u have to override it and then have to call it by the class name.
Interface cant have static method because if you know the static property that method declared static can be called without creating any object of class and sttaic methods are part of class not instance of class, so the answer is that how can you call abstract method till java 7, In java 8 you can declare method as static and call it by interface name dot method name.
Now answer fo final is that , final method is not overriden so how you will override it when class will inherit it
why can't we make Interface methods final?
because if you make a method final then you can not override it and the sole purpose of Interface is to have methods that will be overridden by all those class that implements that Interface.
why can't we make Interface methods static?
In Java 8 it's possible, you can make methods static but that method should have a method body
interface Test{
static void hello(){
System.out.println(“hello world”);
}
}
and you can access this method from a class implementing this Interface by
Test.hello();
Is there a reason one can change the access modifier of an overridden method? For instance,
abstract class Foo{
void start(){...}
}
And then change the package-private access modifier to public,
final class Bar extends Foo{
#Override
public void start(){...}
}
I'm just asking this question out of curiosity.
Java doesn't let you make the access modifier more restrictive, because that would violate the rule that a subclass instance should be useable in place of a superclass instance. But when it comes to making the access less restrictive... well, perhaps the superclass was written by a different person, and they didn't anticipate the way you want to use their class.
The programs people write and the situations which arise when programming are so varied, that it's better for language designers not to "second-guess" what programmers might want to do with their language. If there is no good reason why a programmer should not be able to make access specifiers less restrictive in a subclass (for example), then it's better to leave that decision to the programmer. They know the specifics of their individual situation, but the language designer does not. So I think this was a good call by the designers of Java.
Extending a class means the subclass should at least offer the same functionality to the other classes.
If he extends that, then it is not a problem.
Extending could be be either adding new methods or by offering existing methods to more classes like making a package-access method public.
There is only one, you might want the override to be visible by more classes, since no modifier is default, public broadens that.
The explaination is this:-
It's a fundamental principle in OOP: the child class is a fully-fledged instance of the >parent class, and must therefore present at least the same interface as the parent class. >Making protected/public things less visible would violate this idea; you could make child >classes unusable as instances of the parent class.
class Person{
public void display(){
//some operation
}
}
class Employee extends Person{
private void display(){
//some operation
}
Person p=new Employee();
Here p is the object reference with type Person(super class),when we are calling >p.display() as the access modifier is more restrictive the object
reference p cannot access child object of type Employee
Edit: OK, I changed my answer to fix the problem.
If that couldn't be done, then there would be some cases where a class wouldn't be able to implement an iterface and extend a class because they have the same method with different access modifiers.
public Interface A {
public void method();
}
public abstract classs B {
protected void method();
}
public class AB extends B implements A {
/*
* This would't be possible if the access modifier coulnd't be changed
* to less restrictive
*/
public void method();
}
I'm just curious, wouldn't it be more convinient to allow interfaces to contain implementations of static methods? Such methods could contain short commonly used(by this interface implementors) logic.
Because an interface describes what. It doesn't describe how.
If you really want to add (hide) some logic inside an interface, you may consider adding an inner class (Note: never do it, this just shows what is possible from a pure technical perspective):
public interface Person {
public String getFirstName();
public String getLastName();
public class Util {
public String getName(Person person) {
return person.getFirstName() + " " + person.getLastName();
}
}
}
If you use this, it "feels" a bit like having static method code in the interface:
String fullName = Person.Util.getName(this);
As I said - it's pure technically and I don't see any reason to actually do it. A static method can be located in any class, no need to add it to an interface.
An interface is a contract. It says what an implementing object will have (at minimum), but that's all. It says "this house will have a door, a window, and a chimney".
An abstract class is more like a prefab house. It's not complete (you have to add your own siding, for example) but it has parts already there (there is a space for the door, but the whole fireplace is already setup.
The problem with giving code in interfaces is multiple inheritance. Java doesn't allow it. You can have a class implement many interfaces, because interfaces only promise there will be a method with a given signature.
If interfaces held code, then you could implement 3 of them, each with a method body for myUsefulFunction(String thing)... and now you don't know which one gets called.
That's why abstract classes can have method bodys (because you can only extend one class), but interfaces can't (because you can implement multiple interfaces).
I agree that a static method doesn't make sense in an interface. But i don't understand why java allows static members in an interface. Seems a bit inconsistent.
It's the abstract class or regular class which should implement something. Interfaces are not supposed to have any implementations, but they contain the interface of communicating. So static methods are not allowed.
An interface is a special abstract class with all abstract methods.
You can feel free to create an abstract class of your own that contains (non-abstract) static methods, but then you can only inherit from one of them.
Better yet, create a separate helper class with your static methods.
why we should not use static and abstract for a single method?
the static keyword is defined so that a method can be called by a class name rather then an object. that means the method has to have some sort of definition. but abstract means you do not have any details about what the method does, it is as it says **Abstract**. When you inherit or extend a class you can then define the method.
Think of an interface.
If you are asking about having a static method inside of an abstract class, that is a different story. An abstract class is essentially as mentioned an interface and contains just a template of say functions that you must later on implement by inheriting / extending the class. Once you extend that class the static method does not come along with it (that is by default unless the access modifier is public / protected).
A static method is not inherited. Therefore, making it abstract is a nonsense.
The abstract keyword means that child classes must override the method - this is (one of the ways) Java supports polymorphism. If you want to make it so that subclasses cannot override the method you mark it final. So it would be impossible to have an "abstract final" method since they are the exact opposite of each other.
the static keyword implies final as well - all static method are also final. Thus it is impossible to have a method that is both static and abstract since you would be able to make a method that is abstract and final.
The reason for static being final is that it is bound to the class instead of the instance. That means that the compiler looks it up at compile time rather than runtime to determine which method to call. The reason what it is like that? Arbitrary decision that the designers of Java made - they could have allowed static method to be overridden but decided not to. I don't have any particular insight as to why the chose one over the other unfortunately.
As others have said, static+abstract is nonsense in Java. But there have been (rare) occasions where I've wished I could do just that.
The result I was looking for was basically to say that... "all concrete classes that extent this abstract class (or implement this interface) must provide a static method with this signature." This capability would allow these classes to provide meta-information about themselves.
Normally I have ended up with an instance method in these cases. If you stipulate that concrete implementations must support the default (no-arg) constructior, you can do...
MyInterface obj = MyClassThatImplementsMyInterface.newInstance();
obj.invokeTheMethodIWishWasBothStaticAndAbstract();