Before Java 8 made it possible to declare static methods in interfaces, it was common practice to place these methods in companion utility classes. For example, the java.util.Collections class is a companion to the java.util.Collection interface, and declares static methods that would be more appropriate in the relevant Java Collections Framework interfaces. You no longer need to provide your own companion utility classes. Instead, you can place static methods in the appropriate interfaces, which is a good habit to cultivate.
package com.my.pac21;
/**
* @auther Summerday
*/
public class Test {
public static void main(String[] args) {
int val1 = 5;
int val2 = 6;
//通过创建实现类的对象
Countable b = new CountableCompanion();
System.out.println(b.getNum(val1, val2));
//直接通过接口调用
Countable.getMul(val1,val2);
}
}
interface Countable{
//普通抽象方法
int getNum(int a,int b);
//静态方法
static int getMul(int a,int b){
return a*b;
}
}
//实现接口的实现类
class CountableCompanion implements Countable{
@Override
public int getNum(int a,int b) {
return a+b;
}
}
Before Java 8 made it possible to declare static methods in interfaces, it was common practice to place these methods in companion utility classes. For example, the java.util.Collections class is a companion to the java.util.Collection interface, and declares static methods that would be more appropriate in the relevant Java Collections Framework interfaces. You no longer need to provide your own companion utility classes. Instead, you can place static methods in the appropriate interfaces, which is a good habit to cultivate.
package com.my.pac21;
/**
* @auther Summerday
*/
public class Test {
public static void main(String[] args) {
int val1 = 5;
int val2 = 6;
//通过创建实现类的对象
Countable b = new CountableCompanion();
System.out.println(b.getNum(val1, val2));
//直接通过接口调用
Countable.getMul(val1,val2);
}
}
interface Countable{
//普通抽象方法
int getNum(int a,int b);
//静态方法
static int getMul(int a,int b){
return a*b;
}
}
//实现接口的实现类
class CountableCompanion implements Countable{
@Override
public int getNum(int a,int b) {
return a+b;
}
}