I am having a problem with calling a default method from an interface. Here is my code:
Interface:
public interface Pozdrav {
public static void stat(){
System.out.println("Ja sam staticni metod");
}
default void osn(){
System.out.println("Ja sam osnovni metod");
}
}
Main class:
public class KonkretniPozdrav implements Pozdrav{
public static void main(String[] args) {
Pozdrav.stat();
}
}
Now, I need to call the default method Pozdrav.osn();
but when I do that, I receive this error:
Error:(8, 16) java: non-static method osn() cannot be referenced from a static context.
How do I call this default method?
new KonkretniPozdrav().osn();
In order to call osn
, an instance of Pozdrav
is required.
A default
method (instance member) doesn't mean a static
method (class member). It suggests that the method will have the body in an interface. default
methods provide the default behaviour for implementations. That's why you didn't have to implement osn
in KonkretniPozdrav
.
You need an instance of Pozdrav
to call an instance method on it. For example:
new Pozdrav() {}.osn();
You need a concrete instance to invoke the method on. If you have not yet created a concrete type, you could do so anonymously. Like,
new Pozdrav() {
}.osn();
Outputs
Ja sam osnovni metod
To call non static methods, you should create a instance of the class using the keyword new
, example: KonkretniPozdrav pozdrav = new KonkretniPozdrav();
. To call static methods, you don't need a instance. Just call using CLASS.Method() .
Your main class would appear like it.
public class KonkretniPozdrav implements Pozdrav{
public static void main(String[] args) {
Pozdrav.stat();
KonkretniPozdrav konkretnipozdrav = new KonkretniPozdrav();
konkretnipozdrav.osn();
}
}
A consideration for your code is that interfaces shouldn't have code implemented, except in static
methods and default
methods, which are allowed code in the body. Interfaces are contracts that classes that implement the interface should comply/obey. Normally is a convention start a interface with the letter I to indicate interface, example: IPozdrav . Here a document about Java interfaces .
Maybe, you would look at the difference between Abstract class vs Interfaces
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.