Java——接口

喜歡就關(guān)注我吧,訂閱更多最新消息
目錄
概述
特點(diǎn)
interface修飾public interface 接口名{}implements表示public class 類(lèi)名 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 {
}
/*
測(cè)試類(lèi)
*/
public class JumppingDemo {
public static void main(String[] args){
//Jumpping j = new Jumpping();
Jumpping j = new Cat();
j.jump();
}
}
成員特點(diǎn)
成員變量:
只能是常量
默認(rèn)修飾符:public static final構(gòu)造方法
接口沒(méi)有構(gòu)造方法
一個(gè)類(lèi)如果沒(méi)有父類(lèi),默認(rèn)繼承自O(shè)bject類(lèi)成員方法
只能是抽象方法
默認(rèn)修飾符:public abstract
/*
接口類(lèi)
*/
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();
}
/*
接口實(shí)現(xiàn)類(lèi)
*/
//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");
}
}
/*
測(cè)試類(lèi)
*/
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);
}
}
類(lèi)和接口的關(guān)系
類(lèi)和類(lèi)的關(guān)系:繼承(單繼承、多層繼承)
類(lèi)和接口的關(guān)系:實(shí)現(xiàn)(單實(shí)現(xiàn)、多實(shí)現(xiàn)、在繼承一個(gè)類(lèi)的同時(shí)實(shí)現(xiàn)多個(gè)接口)
接口和接口的關(guān)系:繼承(單繼承、多繼承)
/*
接口1
*/
public interface Inter1 {
}
/*
接口2
*/
public interface Inter2 {
}
/*
接口3
*/
public interface Inter3 extends Inter1, Inter2 {
}
/*
接口實(shí)現(xiàn)類(lèi)
*/
public class InterImpl extends Object implements Inter1, Inter2, Inter3 {
}
抽象類(lèi)和接口的區(qū)別
抽象類(lèi):變量、常量;有構(gòu)造方法;有抽象方法也有非抽象方法
接口:常量;抽象方法
類(lèi)與接口:實(shí)現(xiàn),可以單實(shí)現(xiàn),也可以多實(shí)現(xiàn)
接口:對(duì)行為抽象,主要是行為

評(píng)論
圖片
表情


