接口中静态方法
代码略…………
私有方法(Java
接口中私有方法定义格式:
package privateFunction;
public interface Inter {
default void show1(){
System.out.println('show1开始');
// System.out.println('我爱我的祖国!');
// System.out.println('我爱首都北京!');
show();
//method(); //调用静态私有方法
System.out.println('show1结束!');
}
default void show2(){
System.out.println('show2开始');
// System.out.println('我爱我的祖国!');
// System.out.println('我爱首都北京!');
show();
//method(); //调用静态私有方法
System.out.println('show2结束!');
}
private void show(){
System.out.println('我爱我的祖国!');
System.out.println('我爱首都北京!');
}
static void method1(){
System.out.println('method1开始');
// System.out.println('我爱我的祖国!');
// System.out.println('我爱首都北京!');
//show();//不能使用非静态方法
method();
System.out.println('method1结束!');
}
static void method2(){
System.out.println('method2开始');
// System.out.println('我爱我的祖国!');
// System.out.println('我爱首都北京!');
//show();//不能使用非静态方法
method();
System.out.println('method2结束!');
}
static void method(){
System.out.println('我爱我的祖国!');
System.out.println('我爱首都北京!');
}
}
package privateFunction;
/*
1、定义一个接口Inter,里面有四个方法:两个是默认方法,两个是静态方法。
default void show1()
default void show2()
static void method1()
static void method2()
2、定义接口的一个实现类
InterImpl
3、定义测试类:
InterDemo
在主方法中按照多态的方式创建对象并使用
总结:接口中静态方法只能调用私有静态方法,非静态方法则既可以调用私有静态方法也可以调用默认方法
*/
public class InterDemo {
public static void main(String[] args) {
Inter inter = new InterImpl();
inter.show1();
inter.show2();
Inter.method1();
Inter.method2();
}
}
接口中定义方法格式:publicstatic返回值类型方法名(参数列表){}
默认方法(Java
接口中静态方法
注意事项:接口中默认方法不是抽象方法,所以不强制被重写,但是可以被重写,重写的时候去掉关键字default就行了。public可以省略,但是default不可以被省略。
接口中默认方法格式定义:
publicdefault返回值类型方法名(参数列表){}
范例:publicdefaultvoidshow3(){}
注意事项:静态方法只能通过接口名调用,不能通过实现类名或者对象名调用。public可以省略,但是static不可以省略。
package staticFunction;
public interface Inter {
void show();
default void method(){
System.out.println('default');
}
static void test(){
System.out.println('test');
}
}
package staticFunction;
public class InterImpl implements Inter{
@Override
public void show() {
System.out.println('InterImpl show');
}
@Override
public void method() {
System.out.println('InterImpl method');
}
//test静态方法无法在实现类中重写
}
package staticFunction;
/*
1、定义一个接口Inter,里面有三个方法:一个是抽象方法,一个是默认方法,一个是静态方法。
void show();
default void method();
static void test();
2、定义一个接口的实现类
InterImpl
3、定义一个测试类
在主方法中按照多态的方式创建对象并使用
总结:接口中的静态方法只能使用接口调用,实现类无法重写,无法调用。
*/
public class InterDemo {
public static void main(String[] args) {
Inter inter = new InterImpl();
inter.method();
inter.show();
//inter.test(); 无法使用实现体类调用接口中的方法
Inter.test(); //使用接口调用接口的静态方法
}
}
接口中的默认方法
抽象方法publicabstract修饰
静态方法(Java
什么时候使用,当新创建的类既要实现接口中的方法,又要实现新的方法时,在接口中添加默认方法。新创建的类重写该方法即可。
文章为作者独立观点,不代表股票交易接口观点