1.在jdk 7 或更早版本中,接口里面只能有常量变量和抽象方法。这些接口方法必须由选择实现接口的类实现。
package com.tntxia;
public interface TempI {
public abstract void method(int n);
}
package com.tntxia;
public class Temp implements TempI{
@Override
public void method(int n)
{
if (n % 2 == 0)
System.out.println("geeksforgeeks");
else
System.out.println("GEEKSFORGEEKS");
}
public static void main(String[] args)
{
TempI in1 = new Temp();
TempI in2 = new Temp();
in1.method(4);
in2.method(3);
}
}
2.jdk8 的时候接口可以有默认方法和静态方法功能
public interface TempI {
public abstract void div(int a, int b);
public default void add(int a, int b)
{
System.out.print("Answer by Default method = ");
System.out.println(a + b);
}
public static void mul(int a, int b)
{
System.out.print("Answer by Static method = ");
System.out.println(a * b);
}
}
package com.tntxia;
public class Temp implements TempI{
@Override
public void div(int a, int b)
{
System.out.print("Answer by Abstract method = ");
System.out.println(a / b);
}
public static void main(String[] args)
{
TempI in = new Temp();
in.div(8, 2);
in.add(3, 1);
TempI.mul(4, 1);
}
}
3.Jdk 9 在接口中引入了私有方法和私有静态方法。
package com.tntxia;
public interface TempI {
public abstract void mul(int a, int b);
public default void
add(int a, int b)
{
// private method inside default method
sub(a, b);
// static method inside other non-static method
div(a, b);
System.out.print("Answer by Default method = ");
System.out.println(a + b);
}
public static void mod(int a, int b)
{
div(a, b); // static method inside other static method
System.out.print("Answer by Static method = ");
System.out.println(a % b);
}
private void sub(int a, int b)
{
System.out.print("Answer by Private method = ");
System.out.println(a - b);
}
private static void div(int a, int b)
{
System.out.print("Answer by Private static method = ");
System.out.println(a / b);
}
}
package com.tntxia;
public class Temp implements TempI{
@Override
public void mul(int a, int b)
{
System.out.print("Answer by Abstract method = ");
System.out.println(a * b);
}
public static void main(String[] args)
{
TempI in = new Temp();
in.mul(2, 3);
in.add(6, 2);
TempI.mod(5, 3);
}
}