[Java] I thought about the merits and uses of "interface"

Introduction

I'm just a Java beginner who just recently learned how to inherit classes If you have a wrong opinion, it would be helpful if you could tell us in an easy-to-understand manner. This time, I will introduce the understanding of interface and when it is convenient to use it with concrete examples.

What is interface

interface is used to implement and use the method later without specifically writing the processing content at the beginning. Effective when you want to change the process because the method is implemented later.

Reference article

My view when I knew only the above ---> ** Do you use it when you can't see the previous vision concretely? ** ** ---> ** If you write the code by yourself, do you need to use it? ** ** ---> ** Is it useful when you want to declare variables to be used later and use them together later? ** **

rule

Only ** constants ** and ** methods ** can be defined Also, the member variables of the interface are automatically given "public static final", so they become ** constants **.

Interface definition (example)

interface interface name{
int constant 1= 1;
int constant 2= 2;
String constant 3= "hello";

void Function name for which processing will be written later();
}

What you can do

The constants defined in the interface can be reused with the defined function names! ✌️

Example

Main.java


interface Calc {
  int num1 = 1;
  int num2 = 2;
  String str1 = "multiplication";
  String str2 = "division";

  void calculation();
}

class Multi implements Calc {
  public void calculation() {
    System.out.println(str1);
    System.out.println(num1 * num2);
  }
}

class Divi implements Calc {
  public void calculation(){
    System.out.println(str2);
    System.out.println(num1 / num2);
  }
}

public class Main {
  public static void main(String[] args){
    Multi mlt = new Multi();
    mlt.calculation();

    Divi div  = new Divi();
    div.calculation();
  }
}

Run


$ java Main

multiplication
2
division
0

Constants and functions defined by the interface name *** Calc *** You can see that it is available in the multiplication class *** Multi *** and the division class *** Divi ***

Isn't it the inheritance of the class?

I think some people may have thought

Yes, ** the same thing if you inherit what you defined in the parent class to the child class! ** **

That is not a mistake.

So what are the advantages of ** interface **?

That is, ** you can inherit multiple interfaces at the same time **

In ** class inheritance **, when inheriting a parent class to a child class, The inheriting child class should only be able to specify ** one parent class **.

** "Can handle (inherit) multiple interfaces created earlier" **

That's the advantage of the ** interface ** over ** class inheritance **.

The best moment to use "interface" instead of class inheritance

I thought that the function as an interface would be useful in such a situation.

First, take a look at the code below. Enter *** number of students, number of classrooms, number of grades *** of my own school, Outputs ** population per classroom and population per grade ** at each school

Main.java



//primary school
  interface Primary_school {
  int p_people  = 500;
  int p_classes = 18;
  int p_year    = 6;
  String p_name = "Mine";
  void pcal();
}

//Junior high school
interface Junior_high_school {
  int j_people  = 750;
  int j_classes = 27;
  int j_year    = 3;
  String j_name = "Yoto";
  void jcal();
}

//University
interface University {
  int u_people  = 10000;
  int u_classes = 50;
  int u_year    = 4;
  String u_name = "Tsukuba";
  void ucal();
}

//Class population density
class PopulationDensity implements Primary_school, Junior_high_school, University{//, Junior_high_school, University {
  public void pcal() {
    System.out.print(p_name+"--->");
    System.out.println(p_people / p_classes);
  }
  public void jcal(){
    System.out.print(j_name+"--->");
    System.out.println(j_people / j_classes);
  }
  public void ucal(){
    System.out.print(u_name+"--->");
    System.out.println(u_people / u_classes);
  }
}

//Grade population density
class PopulationPerYear implements Primary_school, Junior_high_school, University{
  public void pcal(){
    System.out.print(p_name+"--->");
    System.out.println(p_people / p_year);
  }
  public void jcal(){
    System.out.print(j_name+"--->");
    System.out.println(j_people / j_year);
  }
  public void ucal(){
    System.out.print(u_name+"--->");
    System.out.println(u_people / u_year);
  }
}

public class Main {
  public static void main(String[] args){
    String pink   = "\u001b[00;35m";
    String cyan   = "\u001b[00;36m";
    String end    = "\u001b[00m";


    PopulationDensity PD = new PopulationDensity();
    System.out.println(pink+"【PopulationPerClass】: "+end);
    PD.pcal();
    PD.jcal();
    PD.ucal();

    PopulationPerYear PPY  = new PopulationPerYear();
    System.out.println(cyan+"【PopulationPerYear】: "+end);
    PPY.pcal();
    PPY.jcal();
    PPY.ucal();
    //div.calculation();
  }
}

Execution result Screen Shot 2019-04-25 at 15.45.11.png

You can see that each class can inherit multiple defined interfaces.

I think this is a very useful function later when multiple people are in charge of developing different input data.

Advantages and disadvantages of class inheritance and interface

Class inheritance interface
merit Can handle variables and functions defined in the parent class Can handle multiple interfaces at the same time
Demerit Only one class can be inherited by one child class Can only handle constants

For the time being, it looks like this today

Updated: 2019/04/25

Recommended Posts

[Java] I thought about the merits and uses of "interface"
I compared the characteristics of Java and .NET
I didn't understand the behavior of Java Scanner and .nextLine ().
About fastqc of Biocontainers and Java
I tried to summarize the basics of kotlin and java
[Java beginner] About abstraction and interface
Traps brought about by the default implementation of the Java 8 interface
I thought about the strategy of introducing Combine in iOS development
I tried to summarize the methods of Java String and StringBuilder
[day: 5] I summarized the basics of Java
[Java / Swift] Comparison of Java Interface and Swift Protocol
About the mechanism of the Web and HTTP
About Java interface
When I was worried about static methods in java interface, I arrived in the order of name interpretation
[Java] About interface
About the classification and concept of Immutable / Mutable / Const / Variable of Java and Kotlin.
I translated the grammar of R and Java [Updated from time to time]
Think about the combination of Servlet and Ajax
About the description order of Java system properties
About the idea of anonymous classes in Java
[Java] The confusing part of String and StringBuilder
About next () and nextLine () of the Scanner class
I touched on the new features of Java 15
Try the free version of Progate [Java I]
I received the data of the journey (diary application) in Java and visualized it # 001
I want to recursively get the superclass and interface of a certain class
About Java functional interface
java (merits of polymorphism)
[Rails] I learned about the difference between resources and resources
Please note the division (division) of java kotlin Int and Int
The comparison of enums is ==, and equals is good [Java]
[Grails] About the setting area and the setting items of application.yml
Talking about the merits of database bind variables ((1) Introduction)
Organizing the current state of Java and considering the future
Java language from the perspective of Kotlin and C #
[JAVA] What is the difference between interface and abstract? ?? ??
[Java] About Objects.equals () and Review of String comparisons (== and equals)
[Technical memo] About the advantages and disadvantages of Ruby
Use of Abstract Class and Interface properly in Java
I learned about the existence of a gemspec file
[Java] [javaSliver] The interface and abstract classes are complicated, so I will summarize them.
A memo about the types of Java O/R mappers and how to select them
About the handling of Null
[Note] Java Output of the sum of odd and even elements
What I researched about Java 8
About an instance of java
What I researched about Java 6
[Ruby] Questions and verification about the number of method arguments
About the description of Docker-compose.yml
What I researched about Java 9
[Java] Set structure of collection class (about HashSet and TreeSet)
Command to check the number and status of Java threads
What should I do after January 2019 regarding the Java payment issue and Java 8 end of support issue?
Java beginners briefly summarized the behavior of Array and ArrayList
I tried JAX-RS and made a note of the procedure
Have you ever thought about the definition of "bad design"?
About the same and equivalent
[Ruby] About the difference between 2 dots and 3 dots of range object.
What I researched about Java 7
[Swift] I thought about compare
Think about the differences between functions and methods (in Java)