Java学习笔记(19):接口的组成更新
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java学习笔记(19):接口的组成更新,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1561字,纯文字阅读大概需要3分钟。
内容图文
接口的组成更新
一:常量
1.接口中的变量默认为常量(默认修饰为public static final)
二:抽象方法
接口中的方法默认为抽象方法(默认修饰为public abstract)
三:默认方法
首先,看下面这个接口:
public interface Myinterface {
void one();
void two();
}
假设该接口有多个实现类,如:
public class Myclass implements Myinterface{
@Override
public void one() {
System.out.println("one");
}
@Override
public void two() {
System.out.println("two");
}
}
如果我们需要在接口中再次添加方法,加入一个three()方法,那么显然Myclass类就会出错,因为我们没有在Myclass中重写three()方法,因此,我们需要使用默认方法修饰three()方法:
(注意:默认方法是带有方法体的)
public interface Myinterface {
void one();
void two();
default void three(){
System.out.println("three");
}
}
默认方法不强制重写,但可以被重写,但是不能再加default:
public class Myclass implements Myinterface{
@Override
public void one() {
System.out.println("one");
}
@Override
public void two() {
System.out.println("two");
}
@Override
public void three() {
System.out.println("重写的three");
}
}
四:静态方法
静态方法由static修饰,只能被接口调用或者被接口中的方法调用,且静态方法不能被重写:
接口:
public interface Myinterface {
void one();
default void two(){
System.out.println("默认方法");
}
static void three(){
System.out.println("静态方法");
}
}
实现类:
public class Myclass implements Myinterface{
@Override
public void one() {
System.out.println("普通方法");
}
}
测试类:
public class Mydemo {
public static void main(String[] args) {
Myinterface f = new Myclass();
f.one();
f.two();
Myinterface.three();
}
}
内容总结
以上是互联网集市为您收集整理的Java学习笔记(19):接口的组成更新全部内容,希望文章能够帮你解决Java学习笔记(19):接口的组成更新所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。