Java界面的完整指南

125 阅读8分钟

Java接口类似于一个能够处理多重继承的类。然而,Java接口没有主体,类必须在访问它们之前实现它们。

为什么在Java中使用接口

实现接口的类必须实现该接口的所有方法。另外,Java编程语言不允许你扩展一个以上的类。但是,你可以在你的类中实现一个以上的接口。

Java接口

Java接口是一个抽象方法的集合。一个接口可以有方法和变量,就像Java类一样,但不同的是,接口中声明的方法默认是抽象的。同样地,在接口中声明的变量默认也是公共的、静态的和最终的。

在类中,多重继承是不可能的。为了消除这个缺点,我们使用一个能够处理多重继承的接口。

如何在Java中声明一个接口

要声明一个接口,请使用接口 关键字。它被用来提供完全的抽象性。这意味着接口中的所有方法都以空的主体来声明,所有的字段都是默认的公共、静态和最终的。

一个实现了接口的类必须实现接口中声明的所有方法。如果我们想实现一个接口,我们必须使用implements关键字。

关于接口的一些重要观点

  1. 它是Java中的一种引用类型。
  2. 它有方法,而且默认情况下,它们是抽象的。
  3. 接口中的数据类型是公共的、静态的和最终的。
  4. 我们不能为一个接口创建一个对象,也就是说,不能实例化。
  5. 接口没有构造函数。
  6. 每当一个类想实现任何接口时,该类需要使用 "实现 "关键字而不是 "扩展"。
  7. 一个接口不能实现另一个接口。如果需要,它必须扩展另一个接口。
  8. 一个在另一个接口内声明的接口被称为嵌套接口。
  9. 在声明的时候,接口变量必须被初始化。否则,编译器会抛出一个错误。
  10. 类不能实现两个具有相同名称但不同返回类型的方法的Java接口。

类和接口的区别

在类中,你可以将变量实例化并创建一个对象。 在接口中,你不能将变量实例化并创建一个对象。 类可以包含具体的(有实现的)方法。 接口不能包含具体的(有实现的)方法。 与类一起使用的访问指定符是私有、保护和公共。 在接口中,只使用一个指定符--公共。

如何声明一个接口

这与声明一个类是一样的。但是,我们必须使用 "interface "关键字来代替类。

Java接口的语法

interface Interface_name
{
   Data types;
   Methods ();
}

如何实现Java接口

请看下面的Ip.java文件的例子:

// AppInterface.java

interface firstInterface
{
  void func();
}
class App implements firstInterface
{
  public void func()
  {
    System.out.println("Implementing interface firstInterface");
  }
}
class AppInterface
{
  public static void main(String []args)
  {
     App app = new App();
     app.func();
  }
}

请看输出:

Java Interface Example

这就是一个类是如何实现一个接口的。首先,它必须提供接口中声明的所有方法的主体;换句话说,这个类必须实现所有的接口方法。

请看第二个例子:

interface car
{
  void drive();
}
class Tesla implements car
{
  public void drive()
  {
     System.out.println("Tesla implementing Car Interface");
  }
}
class AppInterface
{
  public static void main(String []args)
  {
     Tesla models = new Tesla();
     models.drive();
  }
}

请看下面的输出:

Interface in Java Tutorial For Beginners

接口中的方法默认是一种抽象的方法。因此,只要任何类 实现了一个接口,我们就必须定义每一个接口方法;否则,这个类就会变成一个抽象类。 在上面的例子中,drive()是汽车接口中的一个抽象方法,它被定义 在Tesla类中。

Java接口中的继承性

一个类扩展另一个类,同样,一个接口可以扩展另一个接口。这里也 使用extends 关键字来扩展接口。

Inheritance in Java Interface

请看下面这个Java接口继承的代码例子:

// Extend.java

interface Printable
{  
    void print();  
}  
interface Showable extends Printable
{  
    void show();  
}  
class Extend implements Showable
{  
	public void print(){System.out.println("Hello");}  
	public void show(){System.out.println("Welcome");}  
  
	public static void main(String args[])
	{  
	    Extend obj = new Extend();  
	    obj.print();  
	    obj.show();  
        }  
}

其输出结果如下:

code example of Java Interface Inheritance

通过接口进行多重继承

如果类实现了多个接口或扩展了它们,这在Java中被称为接口的多重继承。

请看下面的代码例子:

// Multi.java

//creating interfaces
interface Printable
{  
	//declaring abstarct method
	void print();
}  
interface Showable
{  
	//declaring abstarct method
	void show(); 
} 
//Multi class implememnting multiple inheritance

class Multi implements Printable,Showable
{  
	//defining methods of interface Printable
	public void print(){System.out.println("App");} 
	
	//defining methods of interface Showable
	public void show(){System.out.println("Dividend");}  
  
	//Driver class
	public static void main(String args[])
	{  
		//creating object
		Multi obj = new Multi();
		//calling print method from printable
		obj.print(); 
		
		//calling show method from showable
		obj.show();  
	}  
}

请看下面的输出:

Multiple Inheritance by Interface in Java

为什么不允许通过类进行多重继承而可以通过接口进行?

通过类使用 多重继承会产生歧义,但在接口的情况下,就不会有歧义了。

让我们借助一个例子来说明这一点:

// Mul.java
interface X
{
   public void myMethod();
}
//creating interface
interface Y
{
   public void myMethod();
}
// implementing multiple inheritance
class Mul implements X, Y
{
	//defining methods
   public void myMethod()
   {
       System.out.println("Implementing more than one interfaces");
   }
   public static void main(String args[])
   {
	   //creating object
	   Mul obj = new Mul();
	   obj.myMethod();
   }
}

请看输出:

Why multiple inheritance is not allowed through class but possible by an interface?

接口中的默认方法Java 8

在Java 8之后,有一种方法,我们可以在接口中声明方法体,但我们需要使该方法成为 默认的。

让我们来看看这个例子:

// DefMet.java

interface Drawable
{  
	void draw();  
	default void msg(){System.out.println("default method");}  
}  
class Rectangle implements Drawable
{  
	public void draw(){System.out.println("drawing rectangle");}  
}  
class DefMet
{  
	public static void main(String args[])
	{  
		Drawable d=new Rectangle();  
		d.draw();  
		d.msg();  
	}
}

请看下面的输出:

Default Method in Interface in Java 8

接口中的静态方法Java 8

从Java 8开始,我们可以在一个接口中拥有一个静态方法。请看下面的代码:

// StaMet.java

interface Drawable
{  
	void draw(); // abstract method
	static int square(int a){return a*a;} //static method
}  
class Rectangle implements Drawable
{  
	//delaring abstract method
	public void draw(){System.out.println("drawing rectangle");}  
}  
  //Driver class
class StaMet
{  
     public static void main(String args[])
     {  
	Drawable d=new Rectangle();//creating reference variable
	d.draw();
	System.out.println(Drawable.square(3));  
     }
}

请看下面的输出:

Static Method in Interface in Java 8

Java中的嵌套接口

如果一个接口被声明在另一个接口或类中,那么声明的接口就被称为嵌套接口。嵌套接口用于分组相关的接口,以便于维护这些接口。但是,嵌套接口不能直接使用外部类的引用或我们可以访问的接口。

如果你要用嵌套接口来解题,那么你需要记住两个关键点:

  1. 如果该接口是在另一个接口内声明的,那么它必须是公共的,但是如果它是在一个类内声明的,那么它可以有任何访问修改器。
  2. 嵌套的接口是以隐式静态方式声明的。

在这里,我们将讨论两种类型的嵌套接口--一种是在一个接口中声明的嵌套类,另一种是在一个类中声明的嵌套。

嵌套在一个接口中的接口的例子

请看下面的代码:

// NestedInt1.java

//outer interface creating
interface Showable
{  
  void show();
  //nested interface creating within a interface
  interface Welcome
  {  
    void msg();  
  }  
}
//decalring  a class for  accessing nested interface 
class NestedInt1 implements Showable.Welcome
{ 
// defining the method of nested interface 
  public void msg(){System.out.println("Hello,See this is nested interface");}  
  //main method
  public static void main(String args[]) 
  {
	//upcasting  
    Showable.Welcome welcome=new NestedInt1(); //creating reference here 
    welcome.msg();  
  }
}

请看下面的输出:

nested interface within an interface

正如你在上面的例子中看到的,通过其外部的Showable访问Welcome接口是不能直接访问的。

sun microsystem在一个集合框架中提供了一个嵌套接口Entry。Entry是Map的子接口。Map访问他们.Entry。

我们可以把它想象成一个盒子在另一个盒子里面。如果不打开另一个内盒,我们就无法打开外盒。

类中嵌套接口的例子

现在我们将解释一下类中的嵌套接口:

// NestedInt2.java

// creating class
class Outer
{ 
 
// nested interface
  interface Welcome
  {  
     void msg();
  }
}  
 
//accesing the nested interface creating reference 
class NestedInt2 implements Outer.Welcome
{  
     //defining the method of nested class   
    public void msg(){System.out.println("Hello see, this is a nested interface");}  
  
    public static void main(String args[])
    {  
	
        Outer.Welcome welcome=new NestedInt2();//upcasting   
        welcome.msg();  
    }  
}

请看输出:

Example of the nested interface within a class

接口的优点

  1. 接口为所有的实现类提供了一个契约,所以用接口来编码是很好的,因为实现类不能删除我们正在使用的方法。
  2. 接口是合适的起点,可以在我们的代码中定义类型并创建一个顶层的层次结构。
  3. 由于Java类可以实现多个接口,所以在大多数情况下,最好使用接口作为超类。

请看现实生活中的例子:

// RealLife.java

//creating a  interface 
interface Vehicle { 
      
    // all are the abstract methods. 
    void changeGear(int a); 
    void speedUp(int a); 
    void applyBrakes(int a); 
} 
  
class Bike implements Vehicle 
{ 
      
    int speed; 
    int gear; 
      
     //difining a method to change gear
    public void changeGear(int newGear)
    { 
          
        gear = newGear; 
    } 
      
    // defining a method to measure current speed
	
    public void speedUp(int increment)
    {       
        speed = speed + increment; 
    } 
      
    // a method using a break
	
    public void applyBrakes(int decrement)
    { 
          
        speed = speed - decrement; 
    } 
      
    public void printStates() 
    { 
         System.out.println("speed: " + speed + " gear: " + gear); 
    } 
} 
  
class Car implements Vehicle
{ 
      
    int speed; 
    int gear; 
      
    //defining a method to change gear
	
    public void changeGear(int newGear)
    { 
          
        gear = newGear; 
    } 
      
      // defining a method to measure current speed
    public void speedUp(int increment)
    { 
          
        speed = speed + increment; 
    } 
      
    // a method using the break
	
    public void applyBrakes(int decrement)
    { 
          
        speed = speed - decrement; 
    } 
      
    public void printStates() 
    { 
         System.out.println("speed: " + speed + " gear: " + gear); 
    } 
      
} 
class RealLife { 
      
    public static void main (String[] args) { 
      
        // create an instance of Bike 
		
        // performing operations  
        Bike bike = new Bike(); 
        bike.changeGear(1); 
        bike.speedUp(6); 
        bike.applyBrakes(2); 
          
        System.out.println("Bike present state :"); 
        bike.printStates(); 
          
        // creating instance of a car. 
        Car car = new Car(); 
        car.changeGear(2); 
        car.speedUp(7); 
        car.applyBrakes(3); 
          
        System.out.println("car present state :"); 
        car.printStates(); 
    } 
}

请看下面的输出:

Advantages of Java Interface

本教程就到此为止。