A note on the differences between interfaces and abstract classes in Java

A description to convince yourself about the difference between an interface and an abstract class.

Introduction

Why are there these two? I noticed that many people have the same questions as attending study sessions. I was convinced by myself once, but I forgot, so I decided to remember. Also, make a note here so that you can refer to it at any time if you forget it. I repeatedly asked myself questions and gave convincing explanations, so I would like to record them in a conversational format here. Java beginner A asks questions one after another, and Java intermediate B answers them.

Perhaps it is an explanation that can eliminate the sickness of beginners who have studied Java grammar. In addition, the content of the conversation is a mastication of the sentences written in the following books. For me, who started programming Android without studying Java properly, the explanation was very easy to understand and accurate, and it was helpful.

[Modern Java for Android Engineers](https://www.amazon.co.jp/Android%E3%82%A8%E3%83%B3%E3%82%B8%E3%83%8B%E3% 82% A2% E3% 81% AE% E3% 81% 9F% E3% 82% 81% E3% 81% AE% E3% 83% A2% E3% 83% 80% E3% 83% B3Java-% E5% B1 % B1% E7% 94% B0-% E7% A5% A5% E5% AF% 9B / dp / 477415878X / ref = sr_1_1? ie = UTF8 & qid = 1502351641 & sr = 8-1 & keywords =% E3% 83% A2% E3% 83 % 80% E3% 83% B3java)

Some of the words that Mr. B utters include some original interpretations such as "this is what it is", so I would appreciate it if you could point out any mistakes.

Interfaces and abstract classes

A: "How should I use interfaces and abstract classes properly?" B: "Basically, why not use an interface that allows multiple inheritance?" A: "Then what is the abstract class for? It can't be inherited multiple times like an interface, and the benefits aren't quite clear." B: "The advantage of abstract classes over interfaces is that they can have concrete implementations, whereas interfaces can only have constants and abstract methods ([Modern Java for Android Engineers]( https://www.amazon.co.jp/Android%E3%82%A8%E3%83%B3%E3%82%B8%E3%83%8B%E3%82%A2%E3%81%AE% E3% 81% 9F% E3% 82% 81% E3% 81% AE% E3% 83% A2% E3% 83% 80% E3% 83% B3Java-% E5% B1% B1% E7% 94% B0-% E7% A5% A5% E5% AF% 9B / dp / 477415878X / ref = sr_1_1? ie = UTF8 & qid = 1502351641 & sr = 8-1 & keywords =% E3% 83% A2% E3% 83% 80% E3% 83% B3java) It says that it can also have nested static classes / interfaces, but I won't mention it here), and abstract classes can also have regular methods (hereinafter referred to as "normal methods") and constructors. " A: "Fum Fum" B: "So, for example, if you want all the subordinate classes to have both methods with the same processing content and methods that you want to change the processing content individually, it is better to use an abstract class rather than an interface. The processing is exactly the same. If it's a method, if you write it in a normal method in an abstract class, its child classes can use it as it is. " A: "I want you to give me a concrete example." B: "For example, let's say that" Figure "is the parent class and" Triangle "and" Rectangle "are the child classes. Suppose these classes have the following fields and methods. "

  1. Each class has "width" and "height" in the fields.
  2. It has a method "show_width_and_height ()" that outputs "width" and "height".
  3. It has a method "getArea ()" to find the area.

B: "The code looks like this:"

Figure.java


public abstract class Figure {
    //field
    protected double width;
    protected double height;

    //constructor
    public Figure(double width, double height) {
       this.width = width;
       this.height = height;
    }

    //Output width and height
    public String show_width_and_height() {
        return "The width is" + String.valueOf(width) + "、" 
                                  + "The height is" + String.valueOf(height); 
    }

    //Output area (abstract method)
    pubic abstract double getArea();
}

Triangle.java


public class Triangle extends Figure {
    //constructor
    public Triangle(int width, int height) {
       super(width, height);
    }
    
    //Output the area of the triangle
    @override
    pubic double getArea() {
        return this.width * this.height / 2;
    }
}

Rectangle.java


public class Rectangle extends Figure {
    //constructor
    public Rectangle(double width, double height) {
       super(width, height);
    }
    
    //Output the area of the rectangle
    @override
    public double getArea(){
        return this.width * this.height;
    }
}

B: "Figure is written as an abstract class. Width and height are defined as fields, show_width_and_height () is a normal method, and getArea () is an abstract method. While interface methods are only abstract methods, Recall that you can usually have methods inside an abstract class. Width, height, show_width_and_height () are inherited from the figure to Triangle, Rectangle, so you don't have to rewrite them in the child class. Specific implementation cannot be inherited by a class. " A: "I see!" B: "Then getArea (), but I'm using this as an abstract method, because the area is calculated differently for triangles and quadrilaterals, so I'm trying to leave the contents to each child class." A: "But isn't it possible to make the method for finding the area a normal method with a dummy content and override it? More specifically, getArea () is not written in the figure, but each individual method. You can also write in a child class, right? " B: "It's possible, but there's no guarantee that the person writing the code will implement getArea () in the child class. When you want to guarantee that, the abstract class works well. Can force its own abstract methods to be overridden by subordinate classes, which helps prevent implementation omissions. Well, in this respect it is the same as the interface. " A: "You insist that this feature is essential!" B: "The other difference is that abstract classes belong to a part of the class hierarchy, while the interfaces are independent. It's not accurate, but a rough sketch of the class hierarchy in the Java world. I wrote it, so please check it. "

Javaのクラス階層.png

B: "When defining a class, even if you do not specify the inheritance source, you will implicitly inherit the Object class at the top of the class hierarchy. This will be added to the existing class hierarchy. This means that the interface is independent of the class hierarchy and can be freely associated with any class. Also, the abstract class AbstractMap is a child class of the Object class and the parent of concrete classes such as HashMap and TreeMap. It's a class. It's an abstract class embedded inside a class hierarchy. You can't do this because the interface isn't a class. " A: "It's completely different if you explain it."

Finally

I think I've gained a lot of understanding about how the two are different, but I'm sure there's still a lot to be said about how to use them properly. Apparently [Introduction to Design Patterns Learned in Java Language](https://www.amazon.co.jp/%E5%A2%97%E8%A3%9C%E6%94%B9%E8%A8%82] % E7% 89% 88-Java% E8% A8% 80% E8% AA% 9E% E3% 81% A7% E5% AD% A6% E3% 81% B6% E3% 83% 87% E3% 82% B6 % E3% 82% A4% E3% 83% B3% E3% 83% 91% E3% 82% BF% E3% 83% BC% E3% 83% B3% E5% 85% A5% E9% 96% 80-% E7% B5% 90% E5% 9F% 8E-% E6% B5% A9-ebook / dp / B00I8ATHGW / ref = sr_1_1? ie = UTF8 & qid = 1502444166 & sr = 8-1 & keywords =% E3% 83% 87% E3% 82% B6% E3% 82% A4% E3% 83% B3% E3% 83% 91% E3% 82% BF% E3% 83% BC% E3% 83% B3) It seems that it is written in detail. Actually, I bought it before, but I can't read much. I may add it if there is something new.

Recommended Posts

A note on the differences between interfaces and abstract classes in Java
Understand the difference between abstract classes and interfaces!
Think about the differences between functions and methods (in Java)
Differences in writing Java, C # and Javascript classes
Get a rough idea of the differences between protocols, classes and structs!
Summarize the differences between C # and Java writing
About the difference between classes and instances in Ruby
A note for Initializing Fields in the Java tutorial
[JAVA] What is the difference between interface and abstract? ?? ??
Java classes and instances to understand in the figure
About abstract classes in java
Java abstract methods and classes
[Java] Note about the difference between equivalence judgment and equality judgment when comparing String classes
Differences in how to handle strings between Java and Perl
Differences between "beginner" Java and Kotlin
[JAVA] Difference between abstract and interface
Differences between Java and .NET Framework
Difference between final and Immutable in Java
A note on the libGDX Utils class
[Java] Differences between instance variables and class variables
[Note] Cooperation between Java and DB (basic)
JAVA learning history abstract classes and methods
[Details] Let's master abstract classes and interfaces! !!
A rudimentary note on the Fibonacci sequence
Difference between int and Integer in Java
Specify the order in which configuration files and classes are loaded in Java
The story of forgetting to close a file in Java and failing
Interpret the relationship between Java methods and arguments into a biochemical formula
Understand the difference between int and Integer and BigInteger in java and float and double
[Java] Understand the difference between List and Set
Regarding the transient modifier and serialization in Java
[Java] Difference between equals and == in a character string that is a reference type
About the idea of anonymous classes in Java
A story about the JDK in the Java 11 era
Effective Java 3rd Edition Chapter 4 Classes and Interfaces
Measure the size of a folder in Java
Difference between next () and nextLine () in Java Scanner
[Understanding] Differences between hashes and arrays in Ruby
A note when you want Tuple in Java
Differences between Java, C # and JavaScript (how to determine the degree of obesity)
Compile and run Java on the command line
How to find the distance and angle between two points on a plane
Distinguish between positive and negative numbers in Java
A note about the Rails and Vue process
Upload and download notes in java on S3
Organize your own differences in writing comfort between Java lambda expressions and Kotlin lambda expressions.
[Java] [javaSliver] The interface and abstract classes are complicated, so I will summarize them.
Let's sort out the differences between Java substring and C # Substring, and how to port them.
Understand in 3 minutes! A very rough explanation of the difference between session and cookie
Write ABNF in Java and pass the email address
What is the difference between a class and a struct? ?? ??
Please note the division (division) of java kotlin Int and Int
Differences between Ruby syntax error statements in Ruby and binary
Write a class in Kotlin and call it in Java
Calculate the difference between numbers in a Ruby array
[Java] Difference between static final and final in member variables
Differences between Fetch Type LAZY and EAGER in Hibernate
How to convert A to a and a to A using AND and OR in Java
Use of Abstract Class and Interface properly in Java
Differences in code when using the length system in Java
What is the difference between Java EE and Jakarta EE?