はじめに
第6回はインターフェースである。
インターフェースとは日本語で接点という意味だが、Javaではどのような役割を持つのだろうか。
インターフェースとは
インターフェースとはクラスの一種で、メソッドのシグネチャ(signature)=(メソッド名と引数の型(parameter type))のみを定義して、実装はインターフェースを継承するサブクラスに任せるというもの。
オブジェクト間の契約的(contract)な関係を定義する。
インターフェースの解説
インターフェースはクラスの一種である。
インターフェースの特徴は、
抽象的(abstract):
インターフェース内のメソッドは全て暗黙的にabstract。
フィールドを持たない:
インターフェースはフィールド(fields, variables)を持たない。代わりにRead-Onlyな定数(constants)が使える。
またJava 8以降では、default methodやstatic(静的) methodを用いて、インターフェースのメソッド内に直接処理を書けるようになった。
default method: 実装クラスでオーバーライド可
static method: オーバーライド不可
具体例
// Define the interface public interface Drawable { // Method signature void draw(); } // Class implementing the interface public class Circle implements Drawable { // Implementation of the draw method @Override public void draw() { System.out.println("Drawing a circle"); } } // Main class to demonstrate the use of interfaces public class InterfaceExample { public static void main(String[] args) { // Create an object of the class that implements the interface Circle circle = new Circle(); // Call the method through the interface reference Drawable drawable = circle; drawable.draw(); // Outputs "Drawing a circle" } }
mainメソッド内では、インターフェースの実装クラスのオブジェクトを作成したあとに、インターフェース作成して実装クラスに参照した後、メソッドを呼び出すという流れです。
疑問点
「abstract class と interface の使い分け」
abstract method:
クラスの実装の一部を共有でき、オブジェクト指向的な再利用(継承)に向いている。
interface:
メソッド定義を共有するため、機能の再利用に向いている。
まとめ
ここら辺から似たような概念が出てきてわかりにくくなってきましたが、後から理解されるような類の知識でしょう。
第7回は例外です。
注意
このページは大学のJavaの授業の予習で書いています。
直観的な理解をメモしているだけなので、厳密なところでは誤りがあるかもしれません。