java接口

先看interface例子

interface Animal{
	public void eat();
	public void sayhello();
}

class human implements Animal{
	public void eat(){

	}
}

public class interface_test{
	public static void main(String[] args){
		human h = new human();
	}
}

运行结果:

 编译错误。跟继承抽象类相似,子类必须实现接口所有方法,或者将其定义成抽象类,通过子类的子类来实现

interface Animal{
	public void eat();
	public void sayhello();
}

abstract class human implements Animal{
	public void eat(){

	}
}

class chirld extends human{
	public void sayhello(){
		System.out.println("hello");
	}
}

public class interface_test{
	public static void main(String[] args){
		chirld c = new chirld();
		c.sayhello();
	}
}

运行结果:

     实现接口的方式,与类继承差不多,那接口与类有如下区别

  • 接口不能用于实例化对象。
  • 接口没有构造方法。
  • 接口中所有的方法必须是抽象方法(默认为抽象的)。
  • 接口不能包含成员变量,除了 static 和 final 变量。
  • 接口支持多继承。

    接口和抽象类的区别

  • 抽象类中的方法可以有方法体,就是能实现方法的具体功能,但是接口中的方法不行。
  • 抽象类中的成员变量可以是各种类型的,而接口中的成员变量只能是 public static final 类型的。
  • 接口中不能含有静态代码块以及静态方法(用 static 修饰的方法),而抽象类是可以有静态代码块和静态方法。
  •  一个类只能继承一个抽象类,而一个类却可以实现多个接口
      不仅类能实现继承,接口也可以继承其他接口。java中,类不能多继承,而接口能继承多个接口,类也可以实现多个接口,解决了不能多继承的局限。
interface Animal{
	public void eat();
}
 
interface human extends Animal{
 	public void sayhello();
}

interface man extends Animal,human{
	public void saybye();
}

class chirld implements man{
	public void eat(){
		System.out.println("eat");
	}

	public void sayhello(){
		System.out.println("hello");
	}

	public void saybye(){
		System.out.println("bye");
	}
}

public class interface_test{
	public static void main(String[] args){
		chirld c = new chirld();
		c.eat();
		c.sayhello();
		c.saybye();
	}
}

运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值