接口_java

接口

  • 接口也是一种引用数据类型
  • 接口是完全抽象的 而抽象类是半抽象 所有接口和抽象类一样都不能创建对象(不能进行实例化)
  • 语法:
  • [修饰符列表] 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
{
	// 抽象方法
	// public abstract void sum();

	void sum();
	public static final double PI=3.1415926;
}
接口进行多态(其实是一样的)
public class Test02
{
	public static void main(String[] args){
		// 父类型引用指向子类型对象
		MyMath mm=new MyMathImpl();
		// 这叫做面向接口编程
		// MyMath nn=new MyMath();  报错
		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("飞猪");
	}
}
// 总结:你需要使用什么功能时,你就使用什么接口将它插入

接口和抽象类的区别
  • 抽象类是半抽象,接口是完全抽象
  • 抽象类中有构造方法,接口中没有构造方法
  • 接口和接口之间可以进行多继承 类和类之间只能进行单继承
  • 一个类可以有多个接口,一个抽象类只能继承一个类(单继承)
  • 接口中只允许常量和抽象放法
  • 在以后,接口使用的比抽象类多,接口一般是对”行为“的抽象
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值