はじめに
第5回は抽象クラスである。
オブジェクト指向でたびたび登場するabstractについて解説する。
抽象クラスとは
抽象クラスはOOPにおいて、設計の再利用性(reusability)と拡張性(extensibility)を高めるために利用されるクラス。
オブジェクト指向の「抽象化」の考え方が重要。
抽象クラスの解説
抽象クラスの特徴は、
- 直接インスタンスを作成できない(newできない)
- 完全な実装がされていない抽象メソッドを含むことができる
- サブクラスによって抽象メソッドが実装されることを想定 (サブクラスでオーバライドする)
具体例
// Abstract class abstract class Animal { protected String name; public Animal(String name) { this.name = name; } // Abstract method (does not have a body) public abstract void makeSound(); // Concrete method (has a body) public void eat() { System.out.println(name + " is eating."); } } // Concrete subclass class Dog extends Animal { public Dog(String name) { super(name); } // Implement the abstract method @Override public void makeSound() { System.out.println("Woof!"); } } // Main class to demonstrate the use of abstract classes public class AbstractClassExample { public static void main(String[] args) { // Create an object of the concrete subclass Dog dog = new Dog("Buddy"); // Call the concrete method inherited from the abstract class dog.eat(); // Outputs "Buddy is eating." // Call the abstract method implemented in the concrete subclass dog.makeSound(); // Outputs "Woof!" } }
上の例からわかるように、抽象クラスや(サブクラスでオーバーライドされていない)抽象メソッド単体では意味をなさない。mainメソッドの中を見ると、
newで作成したのはサブクラスの具象クラス(concrete class)である。
dog.eat()は、抽象クラス内の具象メソッドを呼び出している。
dog.makeSound()は、抽象クラス内の抽象メソッド(但し、サブクラスでオーバーライドされて実装された)を呼び出している。
疑問点
「サブクラス内のメソッドの中身にある、super()って何?」
サブクラスのコンストラクタから、スーパークラスのコンストラクタを呼び出す際に用いる。また、super.method()とすることでオーバーライドしたスーパークラスのメソッドを呼び出せる。つまり、(super)=(superclass名) である。
まとめ
抽象クラスを用いることで、クラスのメソッドをサブクラスを作っていい感じに使い分けられて、元の抽象クラスは煩雑にならなくて済む、といった感じでしょうか。
第6回はインターフェースです。
注意
このページは大学のJavaの授業の予習で書いています。
直観的な理解をメモしているだけなので、厳密なところでは誤りがあるかもしれません。