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”.
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:
implements
(! extends
) must be usedinterface interface_name{
public abstract return_value_type function_name(Parameters){
/*****************/
/***Description***/
/*****************/
}
}
abstract
can be omittedpublic
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();
}
}
implements
) the interface.We mentioned the concept of inheritance in [Day 21: Inheritance (1)] (https://ithelp.ithome.com.tw/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.
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.