0

What is difference between this codes in java 8 :

This :

public class Hello {
    public static void sayHello() {
        System.out.println("ghasedak.Hello !!!");
    }
}

and this :

public interface Hello {
    public static void sayHello() {
        System.out.println("ghasedak.Hello !!!");
    }
}

This is main class :

public class MainClass {
    public static void main(String[] args) {
            Hello.sayHello(); //for function
            Hello.sayHello(); //for class
    } 
}
mah454
  • 1,571
  • 15
  • 38

3 Answers3

0

In Java 8 you are now allowed to define methods in interfaces. So technically they are the same. The difference with interfaces still remains you cannot instantiate them. So you can only use the methods in them.

Here is link: https://en.wikipedia.org/wiki/Interface_(Java)

It speaks about how interfaces interact now in Java 8.

In your code, it still should call the Hello class method over the interface class method because as I said interfaces can't be instantiated.

RostSunshine
  • 216
  • 4
  • 14
0

There is no difference between the two.

The first example shows a static method implemented in a class while the second one shows a static method implemented in an interface. The second example wouldn't compile if you use JDK 7 or below because as others have already said, static method support in interfaces was only added in Java 8. Here is a very useful StackOverflow article that explains why the support for static and default methods in interfaces was added in Java 8.

The choice of whether you want to keep your static method, which may be a utility method, in a class or an interface, depends on the circumstances. E.g. if you want to add a new common method to a set of classes that do not extend a common base class but do implement a common interface. You might add the common method to the interface since there is no common base class.

VHS
  • 9,534
  • 3
  • 19
  • 43
0

I think we have two difference :
1) interfaces can only have one function .
2) important : interface is not class , so have not block static :
view this code :

public class Hello {
    static {
        System.out.println("Ok");
    }
    public static void sayHello() {
        System.out.println("ghasedak.Hello !!!");
    }
}

this block run when you call class .
you can not do this on function interfaces . (intefaces have not this block)
sorry for bad english language

mah454
  • 1,571
  • 15
  • 38