5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Scalaのclassとobjectの違い

Last updated at Posted at 2019-10-16

初投稿です
Scalaを勉強し始めたので、Scalaの特徴で「へー」と思ったので書いてきます。

classとobjectの違いを見ていこう

コメントでばーっと書きました

// FujiClassって名前のclass作成
class FujiClass {
  // speakメソッドを呼んだらpritlnが起こる
  def speak() = println("クラナドは人生")
}
// FujiObjectって名前のobject作成
object FujiObject {
  // speakメソッドを呼んだらpritlnが起こる
  def speak() = println("efも面白いから見ろ")
}
object Main {
  def main(args: Array[String]): Unit ={
    // classの場合、インスタンスを作成して
    val u = new FujiClass()
    // メソッドを使う
    u.speak()  //=> 「クラナドは人生」とコンソールにでる


    // objectの場合、インスタンスがいらない
    FujiObject.speak() //=> 「efも面白いから見ろ」とコンソールにでる
  }
}

まとめ

classの中のメソッド使うにはインスタンス作成する必要あり、javaと一緒やね
objectの中のメソッドを使うには クラス名.メソッド名 でok、javaでいうstaticメソッドやね

5
1
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
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?