Day 26 : Interface

Chi-Tse Chiang
2022-10-11 23:41:55

Intro

The concept of an interface is similar to abstraction and should be familiar to us. The purpose is the same: to protect specific data.

It consists of a way of dealing with abstraction, in other words, it is a concept made up of abstract categories.

But when it comes to this issue, why do we need to use an interface in particular?

This will be explained in the following section, Multiple Interfaces.

Rule

Like abstract concepts, objects that cannot establish an interface, and the functions within them, cannot define initial content.

However, there are some slightly different parts:

1. The variables declared in the interface must be initialized

2. The interface does not have a constructor because of (1.)

3. To inherit an interface, the keyword implements (! extends) must be used

4. Functions only have abstract types, as shown in the following format

interface interface_name{
	public abstract return_value_type function_name(Parameters){
		/*****************/
		/***Description***/
		/*****************/
	}
}

Because all functions in the interface are of type abstract, the keyword abstract can be omitted

To read the content, the function modifier can only be default or public

Example

interface School {
  public abstract void performance();
  public void grade();
}

class Student implements School {
  public void performance(){
    System.out.println("You did a great job !!!");
  }

  public void grade(){
    System.out.println("You got A !!!");
  }
}

public class Main{
  public static void main(String[] args) {
    Student new_obj = new Student();   //透過子類別繼承類別創造物件
    new_obj.performnace();
    new_obj.grade();
  }
}

Subclasses inherit interface members and can be thought of as implementing (implements) the interface.

Multi-Interface

We mentioned the concept of inheritance in [Day 21: Inheritance (1)] (/articles/10305142)

In Java inheritance is always unidirectional.
The meaning is that a child class cannot inherit from 2 or more parent classes at the same time. This is actually not entirely true.

Child classes that inherit from interface types can inherit from 2 or more parent classes at the same time

as long as they are all superclasses of the interface!!!

interface One {
  public void One_Function();
}

interface Two {
  public void Two_Function();
}

class sub_can_inhermutli implements One,Two{
  public void One_Function() {
    System.out.println("First interface contents");
  }
  public void Two_Function() {
    System.out.println("Second interface contents");
  }
}

public class Main {
  public static void main(String[] args) {
    sub_can_inhermutli new_obj = new sub_can_inhermutli();
    new_obj.One_Function();
    new_obj.Two_Function();
  }
}

Subcategories can inherit multiple interfaces. Note that the inherited interfaces should be separated by commas.