0
interface temp
{
   public int add(int a,int b)
   {
      return a+b;
   }
}

can we implement method like above in interface, or we have to just define methods in interface.

M.Usman
  • 2,049
  • 22
  • 25
  • 1
    @BackSlash: that thread is out of date. In the current versions of Java, it is possible to have implemented methods in interfaces, allbeit default methods. – Stultuske Nov 25 '15 at 12:58
  • @Stultuske Did you read the thread in question ? The accepted answer is all about that. – Alexis C. Nov 25 '15 at 12:59
  • @AlexisC.: no doubt that's why they were going gung ho on Java 6 – Stultuske Nov 25 '15 at 13:00
  • I agree the duplicate is a bit off, because it talks about static methods (default methods are only mentioned in passing). Either way, with Java 8, you have these two options now. Before that, you had neither. – Thilo Nov 25 '15 at 13:00
  • See also https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html for further informations. – Alexis C. Nov 25 '15 at 13:03

2 Answers2

8

Yes you can in Java 8, using default methods

interface temp
{
   default public int add(int a,int b)
   {
      return a+b;
   }
}

As mentioned by Thilo in the comments, Java 8 also added the possibility to have static methods in interfaces:

interface temp
{
   public static int add(int a,int b)
   {
      return a+b;
   }
}
wero
  • 32,544
  • 3
  • 59
  • 84
  • Nitpicking: Since OP is asking about *any* method then answer is no because we can't implement this way methods from Object class like `equals` or `toString`. – Pshemo Nov 25 '15 at 12:58
  • Nitpicking response: OP was asking if we can implement *any* methods. Not *every* method. – Thilo Nov 25 '15 at 13:06
  • But what happens if you provide a default for `toString` in your interface? Some compile error on the class that implements it (asking it to explicitly specify which `toString` it wants to inherit)? – Thilo Nov 25 '15 at 13:09
  • 1
    @Thilo I think it is never used since the inherited `toString` from the parent class or `Object` always has precedence – wero Nov 25 '15 at 13:11
  • Without any warning? That would be a pity/confusing. I kind of expect to get an error. What happens when you inherit the same default method from two interfaces? – Thilo Nov 25 '15 at 13:12
  • @Thilo this gives a compiler error – wero Nov 25 '15 at 13:36
  • 1
    @Thilo It indeed produces a compile error. Concerning your second point, if you inherit the same default method, you are forced to provide an implementation, either by explicitly delegates the call to one of the interface or by providing your own implementation. – Alexis C. Nov 25 '15 at 13:36
0

If you are not using java 8 then you can only define methods in interface.

 public interface temp {
     int add(int a,int b);
}

This is a new feature "default method in interface" introduced in java 8.

RockAndRoll
  • 2,247
  • 2
  • 16
  • 35