Scala의 class

JJStone·2022년 2월 17일
0

Scala 기초

목록 보기
4/5

Class

  1. class 선언

    • class로 선언 했다면 해당 클래스의 객체를 생성할 때, new 연산자로 객체를 생성해야한다.
    // 괄호 안의 부분이 생성자라고 보면 됨. var를 안쓰면 default,val immutable, var는 mutable.
    /// val 또는 var를 쓸 경우 외부에서 참조 가능 
    
    class Test(val p1 : Int, p2 : Short, var p3 : Int){  
      override def toString: String = s"($p1, $p2, $p3)"
    }
    
    object Test {
      def main(args: Array[String]): Unit = {
        val test = new Test(1,2, 3);
        println(test.toString) // out : (1,2,3)
        test.p3 = 1
        println(test.p1) // out : 1
        println(test.toString) // out : (1,2,1)
        test.p2 = 1 // 컴파일 에러
      }
    }
    • 생성자 파라미터에 defalt값을 지정해줄 수 있다.
    class Test(p1 : Int, p2 : Short, var p3 : Int = 9999){ 
       override def toString: String = s"($p1, $p2, $p3)"
    }  
    
    object Test {
      def main(args: Array[String]): Unit = {
      // default 값을 넣을 경우 파라미터 순서가 꼬일 수 있다.
      // 어떤 파라미터에 해당 값을 집어넣어줄지를 명시해주는것이 좋다.
        val test = new Test(p1 = 1, p2 = 2) 
        println(test.toString) // out : (1,2,9999)
      }
    }
    • 접근 제어 지정자
    class Test(p1 : Int, p2 : Int){
      private def sumInner = (p1 + p2) // private
      protected def sumInner2 = (p1 + p2) // protected
      def sum = (p1 + p2) // 안쓰면 public 
    
    }
    
    object Main {
      def main(args: Array[String]): Unit = {
        val test = new Test(p1 = 1, p2 = 2)
        println(test.sumInner) // 컴파일 에러
        println(test.sumInner2) // 컴파일 에러
        println(test.sum) // out : 3 
    
      }
    }
    
    • 만일 class에서 static 필드를 생성하고 불러오고 싶다면 object를 쓰면 된다.

Object

  • object는 위에서 언급했듯, Java의 static과 동일하다. 만약 class 이름과 object이름이 같을 때, 이를 Companions(동반자)라고 지칭한다.

  • object의 선언과 사용

    class Test(p1 : Int, p2 : Int){
       private def sumInner = (p1 + p2) 
       protected def sumInner2 = (p1 + p2) 
       def sum = (p1 + p2) 
     
     }
     
     // 싱글톤이기 때문에 생성자를 쓸 경우 컴파일 에러가 발생한다.
     // 싱글톤이란? : 객체의 인스턴스가 단 '1개'만 생성되는 것.
     object Test{ 
       val testVal = 9999;
       def div(p1 : Int, p2 : Int) : Double = (p1 / p2)
     }
     
     object Main {
       def main(args: Array[String]): Unit = {
         println(Test.div(4,2)) // out : 2.0
         println(Test.testVal) // out : 9999
     
       }
     }
    

Trait

  • 자바의 인터페이스와 유사하다. 다만 함수의 구현부를 가질수 있으며, Mixin(클래스는 여러개의 trait을 상속받을수 있다!)를 할 수 있다.

  • Mixin은 with 키워드를 사용해서 할 수 있다.

  • 예제

    trait Animal{
       val name : String
       def bark{
         println(s"${name}이 짖습니다.")
       }
       def print;
     }
     trait Hand{
       val h_count : Int
     }
     trait Foot{
       val f_count : Int
     }
     
     class Dog(val name : String, val h_count: Int, val f_count : Int, personality : String) extends Animal with Hand with Foot { // Mixin
       override def print: Unit ={
         println(s"이름은 ${name}인 ${h_count+f_count}발 달린 개가 ${personality}같은 성격을 지녔습니다.")
       }
     }
     
     class Cat(val name : String, val h_count: Int, val f_count : Int) extends Animal with Hand with Foot { // Mixin
       override def print: Unit ={
         println(s"이름은 ${name}인 ${h_count+f_count}발 달린 고양이입니다.")
       }
     }
     
     object Main {
       def main(args: Array[String]): Unit = {
         val Charles = new Dog("Charles",2, 2, "댕댕이");
         val Adolph = new Cat("Adolph", 2, 2)
     
         Charles.bark
         Adolph.bark
         Charles.print
         Adolph.print
     
       }
     }
     
     /** stdout
      * Charles이 짖습니다.
      * Adolph이 짖습니다.
      * 이름은 Charles인 4발 달린 개가 댕댕이같은 성격을 지녔습니다.
      * 이름은 Adolph인 4발 달린 고양이입니다.
      */
    
profile
java, scala 개발자 입니다.

0개의 댓글