LoginSignup
1
0

More than 5 years have passed since last update.

がばがばscala独学-クラス(2)

Posted at

はじめに

下記のテキストを通して、基本的な書き方を学びつつ、個人的に気になったことを検証していくメモ代わりです。
https://dwango.github.io/scala_text/basic.html
本当にありがとう、dwango様・・・

クラス

  • ざっくりまとめ
    • 継承は実装の再利用や処理の共通化をするために使用
    • override漏れがあった場合はコンパイルエラーとなるため安心して実装可能

継承

  • 継承の目的

    • スーパークラスの実装による、サブクラスでの実装の再利用
    • スーパークラスのインタフェースによる、複数サブクラスでの処理の共通化
  • 一般型

    class SubClass(....) extends SuperClass {
      ....
    }
    
  • override

    • 既存メソッドの上書き処理
    scala> class PrinterSuperClass() {
         |     def print(): Unit = {
         |         println("super class")
         |     }
         | }
    defined class PrinterSuperClass
    
    scala> new PrinterSuperClass().print
    super class
    
    --------------------------------------
    
    scala> class PrinterSubClass() extends PrinterSuperClass{
         |
         | }
    defined class PrinterSubClass
    
    scala> new PrinterSubClass().print
    super class
    
    --------------------------------------
    
    scala> class PrinterSubClass() extends PrinterSuperClass{
         |     def print(): Unit = {
         |         println("sub class")
         |     }
         | }
    <console>:9: error: overriding method print in class PrinterSuperClass of type ()Unit;
     method print needs `override' modifier
               def print(): Unit = {
                   ^
    --------------------------------------
    
    scala> class PrinterSubClass() extends PrinterSuperClass{
         |     override def print(): Unit = {
         |         println("sub class")
         |     }
         | }
    defined class PrinterSubClass
    
    scala> new PrinterSubClass().print
    sub class
    
    • 同名関数をoverrideせずに定義すると needs override modifierと出るためオーバーライド漏れはない
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0