温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

在Java中实现接口的方法

发布时间:2020-08-20 14:30:47 来源:亿速云 阅读:287 作者:小新 栏目:编程语言

小编给大家分享一下在Java中实现接口的方法,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

在java中,接口像类一样,可以有方法和变量,但在接口中声明的方法默认是抽象的(只有方法签名,没有主体)。

接口是指定类必须执行什么操作,而不是如何操作。如果类实现了接口并且没有为接口中指定的所有函数提供方法体,则必须将类声明为抽象的。

接口的基本语法:

interface <interface_name> {
    
    // 声明常量字段
    // 声明抽象方法
    // 默认情况下
}

要声明接口,请使用interface关键字。它用于提供完全抽象。这意味着接口中的所有方法都是使用空主体声明的,并且是公共的,默认情况下所有字段都是public,static和final。

要实现接口,请使用implements关键字。实现接口的类必须实现接口中声明的所有方法。

为什么要使用接口?

1、它用于实现完全抽象。

2、由于java在类的情况下不支持多重继承,但是通过使用接口它可以实现多重继承。

3、它还用于实现松耦合。

4、接口用于实现抽象。所以问题出现了为什么在我们有抽象类时使用接口?

原因是,抽象类可能包含非final变量,而interface中的变量是final,public和static。

// 一个简单的接口
interface Player 
{ 
    final int id = 10; 
    int move(); 
}

接口的的实现

要实现接口,我们使用关键字:implement

简单实例:

让我们考虑一个Bicylce, Bike, car等车子的例子,它们有共同的功能。所以我们建立了一个接口并把所有这些共同的功能放在一起。让Bicylce, Bike, car…等等用他们自己的方式在他们自己的类里实现所有这些特征。

import java.io.*; 

interface Vehicle { 
	
	// 一切都是抽象的方法
	void changeGear(int a); 
	void speedUp(int a); 
	void applyBrakes(int a); 
} 

class Bicycle implements Vehicle{ 
	int speed; 
	int gear; 
	
	// 换档
	@Override
	public void changeGear(int newGear){ 
		
		gear = newGear; 
	} 
	
	// to increase speed 
	@Override
	public void speedUp(int increment){ 
		
		speed = speed + increment; 
	} 
	
	// 降低速度
	@Override
	public void applyBrakes(int decrement){ 
		
		speed = speed - decrement; 
	} 
	
	public void printStates() { 
		System.out.println("speed: " + speed 
			+ " gear: " + gear); 
	} 
} 

class Bike implements Vehicle { 
	
	int speed; 
	int gear; 
	
	// to change gear 
	@Override
	public void changeGear(int newGear){ 
		
		gear = newGear; 
	} 
	
	// to increase speed 
	@Override
	public void speedUp(int increment){ 
		
		speed = speed + increment; 
	} 
	
	// to decrease speed 
	@Override
	public void applyBrakes(int decrement){ 
		
		speed = speed - decrement; 
	} 
	
	public void printStates() { 
		System.out.println("speed: " + speed 
			+ " gear: " + gear); 
	} 
	
} 
class GFG { 
	
	public static void main (String[] args) { 
	
		// creating an inatance of Bicycle 
		// doing some operations 
		Bicycle bicycle = new Bicycle(); 
		bicycle.changeGear(2); 
		bicycle.speedUp(3); 
		bicycle.applyBrakes(1); 
		
		System.out.println("Bicycle present state :"); 
		bicycle.printStates(); 
		
		// creating instance of bike. 
		Bike bike = new Bike(); 
		bike.changeGear(1); 
		bike.speedUp(4); 
		bike.applyBrakes(3); 
		
		System.out.println("Bike present state :"); 
		bike.printStates(); 
	} 
}

在Java中实现接口的方法

看完了这篇文章,相信你对在Java中实现接口的方法有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI