Java——接口

喜歡就關注我吧,訂閱更多最新消息
目錄
概述
特點
interface修飾public interface 接口名{}implements表示public class 類名 implements 接口名{}/*
接口
*/
public interface Jumpping {
public abstract void jump();
}
public class Cat implements Jumpping{
@Override
public void jump() {
System.out.println("貓?zhí)?);
}
}
public abstract class Dog implements Jumpping {
}
/*
測試類
*/
public class JumppingDemo {
public static void main(String[] args){
//Jumpping j = new Jumpping();
Jumpping j = new Cat();
j.jump();
}
}
成員特點
成員變量:
只能是常量
默認修飾符:public static final構造方法
接口沒有構造方法
一個類如果沒有父類,默認繼承自Object類成員方法
只能是抽象方法
默認修飾符:public abstract
/*
接口類
*/
public interface Inter {
public int n = 10;
public final int m = 20;
// public static final int p = 20;
int p = 30;
//public Inter(){}
//public void show(){}
public abstract void method();
void show();
}
/*
接口實現(xiàn)類
*/
//public class InterImpl extends Object implements Inter{}
public class InterImpl implements Inter {
public InterImpl() {
super();
}
@Override
public void method() {
System.out.println("method");
}
@Override
public void show() {
System.out.println("show");
}
}
/*
測試類
*/
public class InterfaceDemo {
public static void main(String[] args) {
Inter i = new InterImpl();
//i.n = 20;
System.out.println(i.n);
//i.m = 40;
System.out.println(i.m);
System.out.println(Inter.m);
}
}
類和接口的關系
類和類的關系:繼承(單繼承、多層繼承)
類和接口的關系:實現(xiàn)(單實現(xiàn)、多實現(xiàn)、在繼承一個類的同時實現(xiàn)多個接口)
接口和接口的關系:繼承(單繼承、多繼承)
/*
接口1
*/
public interface Inter1 {
}
/*
接口2
*/
public interface Inter2 {
}
/*
接口3
*/
public interface Inter3 extends Inter1, Inter2 {
}
/*
接口實現(xiàn)類
*/
public class InterImpl extends Object implements Inter1, Inter2, Inter3 {
}
抽象類和接口的區(qū)別
抽象類:變量、常量;有構造方法;有抽象方法也有非抽象方法
接口:常量;抽象方法
類與接口:實現(xiàn),可以單實現(xiàn),也可以多實現(xiàn)
接口:對行為抽象,主要是行為

評論
圖片
表情


