接口
- 接口也是一种引用数据类型
- 接口是完全抽象的 而抽象类是半抽象 所有接口和抽象类一样都不能创建对象(不能进行实例化)
- 语法:
- [修饰符列表] interface 接口名 {}
- 接口中只包含两部分 一部分是:常量 一部分是:抽象方法
- 接口中的所有元素都是public 修饰 (都是公开的)
- 接口中的抽象方法定义时,可以将 public abstract 可以省略
- 接口中的定义常量时,可以将public static final省略
- 接口和抽象类都可以使用多态 条件:要子类继承父类 子类不是抽象类或者接口 原因:还是因为使用 多态时 程序编译时是一种数据类型 运行时又是另外一种数据类型
public class Test01
{
public static void main(String[] args){
System.out.println(MyMath.PI);
}
}
interface A
{
}
interface B
{
}
interface C extends A,B
{
}
interface MyMath
{
void sum();
public static final double PI=3.1415926;
}
接口进行多态(其实是一样的)
public class Test02
{
public static void main(String[] args){
MyMath mm=new MyMathImpl();
int a=mm.sum(20,20);
System.out.println(a);
}
}
interface MyMath
{
double PI=1.1415926;
int sum(int a,int b);
int sub(int a ,int b);
}
class MyMathImpl implements MyMath
{
public int sum(int a,int b){
return a+b;
}
public int sub(int a,int b){
return a-b;
}
}
public class Test03
{
public static void main(String[] args){
A a=new D();
B b=new D();
C c=new D();
if(a instanceof B)
{
B bb=(B)a;
bb.m2();
}
}
}
interface A
{
void m1();
}
interface B
{
void m2();
}
interface C
{
void m3();
}
class D implements A,B,C
{
public void m1(){}
public void m2(){
System.out.println("m2----");
}
public void m3(){}
}
继承和多态都存在时 代码应该怎么写??
public class Test04
{
public static void main(String[] args){
Animal s=new Cat();
Flyable k=new Cat();
k.fly();
Flyable f2=new Pig();
f2.fly();
}
}
class Animal
{
}
interface Flyable
{
void fly();
}
class Cat extends Animal implements Flyable
{
public void fly()
{
System.out.println("飞猫起飞");
}
}
class Pig extends Animal implements Flyable
{
public void fly()
{
System.out.println("飞猪");
}
}
接口和抽象类的区别
- 抽象类是半抽象,接口是完全抽象
- 抽象类中有构造方法,接口中没有构造方法
- 接口和接口之间可以进行多继承 类和类之间只能进行单继承
- 一个类可以有多个接口,一个抽象类只能继承一个类(单继承)
- 接口中只允许常量和抽象放法
- 在以后,接口使用的比抽象类多,接口一般是对”行为“的抽象