--------------接口---------------
***只能出现常量,和方法【方法不能加方法体】
***接口是完全抽象的。
接口我们可以看作是抽象类的一种特殊情况,在接口中只能定义抽象的方法和常量
-
在 java 中接口采用【修饰符列表】 interface 接口名
{
} 声明 -
接口中的方法默认都是 public abstract 的,不能更改
-
接口中的变量默认都是 public static final 类型的,不能更改,所以必须显示的初始
化 -
接口不能被实例化,接口中没有构造函数的概念
-
接口之间可以继承【支持多继承,,但接口之间不能实现{ 接口中,只含有常量和抽象方法,接口中没有其他内容。
-
接口中的方法只能通过类来实现,通过implements 关键字
-
如果一个类实现了接口,那么接口中所有的方法必须实现
-
一类可以实现【实例化】多个接口
public interface 接口test{
public static void main(String[] args) {
System.out.println(A.Pi);
}
}
interface A{
double Pi= 3.1415926;//常量中的 public static 可以省略
}
interface B extends A{//接口是可以被继承的
}
interface Match{
double Pi= 3.1415926;//常量中的 public static 可以省略
int sum(String A);//接口中可以有方法。
}
interface aas{
//接口中的方法不能有方法体
}
1,类和类之间叫做继承,类和接口之间叫做实现。
继续使用 extends 关键字继承
实现接口 用 implements完成
2,***:当一个非抽象的类,实现接口,必须将接口中的所有方法全部覆盖,或者重写。
实例化接口
public class 接口{
public static void main(String[] args) {
//能用多肽嘛? 可以
Match mm = new MatchTest();
int 结果1 = mm.sum(10, 20);
System.out.println(结果1);
}
}
interface Match{
Double PI = 3.1415926;
int sum(int a, int b);
int sub(int a, int b);
}
// 编写一个类(这个类是一个非抽象类)
// 类的名字是随意的
class MatchTest implements Match{
public int sum(int a, int b) {
return a + b;
}
public int sub(int a, int b) {
return a - b;
}
}
****一个类可以同时实现多个接口(这种机制弥补了java中的单继承)
public class 接口语法{
public static void main(String[] args) {
A AAA= new D();
AAA.m1();
B BBB = new D();
C CCC = new D();
BBB.m2();
CCC.m3();
B BB = (B)AAA;
// 无论在什么时候 类型强制转化,只适用于继承,但不适用于接口。
// 经过测试,接口与接口之间没有继承关系,也可以强制转换,
// 但是一定要注意,运行时,可能会出现ClassCastExcepotion异常
}
}
interface A{
void m1();
}
interface B{
void m2();
}
interface C{
void m3();
}
class D implements A,B,C{
public void m1() {
}
public void m2() {
}
public void m3() {
}
}
当同时出现extends 和interface同时存在的代码
extends 和 interface 同时出现时 extends在前,interface在后。
{
}
public class 接口继承和实现都存在{
public static void main(String[] args) {
飞翔 f = new 猫();
f.fly();
飞翔 猪1 = new 猪();
猪1.fly();
}
}
//动物类是父类,
class 动物类{
}
//可飞翔的接口。
interface 飞翔{
void fly();
}
class 猫 extends 动物类 implements 飞翔{
@Override
public void fly() {
System.out.println(“飞猫起飞”);
}
}
class 猪 extends 动物类 implements 飞翔{
@Override
public void fly(){
System.out.println(“想飞就给猪插上翅膀”);
}
}