English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
클래스는 객체의 추상적이며, 객체는 클래스의 구체적인 예시입니다. 클래스는 추상적이며 메모리를 사용하지 않으며, 객체는 구체적이며 저장 공간을 사용합니다. 클래스는 객체를 생성하는 블루프린트이며, 특정 유형의 객체에 포함된 메서드와 변수를 정의하는 소프트웨어 템플릿입니다.
클래스의 객체를 생성하기 위해 new 키워드를 사용할 수 있습니다. 다음 예제와 같이:
class Point(xc: Int, yc: Int) { var x: Int = xc var y: Int = yc def move(dx: Int, dy: Int) { x = x + dx y = y + dy println("x의 좌표점: " + x); println("y의 좌표점: " + y); } }
Scala의 클래스는 public으로 선언되지 않으며, Scala 소스 파일에는 여러 개의 클래스가 포함될 수 있습니다.
위 예제의 클래스 정의는 두 개의 변수를 정의했습니다 x 및 y 메서드:move메서드는 반환 값이 없습니다.
Scala의 클래스 정의에는 파라미터가 있으며 이를 클래스 파라미터라고 합니다. 예를 들어 위의 xc, yc와 같이 클래스 파라미터는 클래스 전체에서 접근할 수 있습니다.
계속 new 키워드를 사용하여 클래스를 인스턴스화하고 클래스의 메서드와 변수에 접근할 수 있습니다:
import java.io._ class Point(xc: Int, yc: Int) { var x: Int = xc var y: Int = yc def move(dx: Int, dy: Int) { x = x + dx y = y + dy println("x의 좌표점: " + x); println("y의 좌표점: " + y); } } object Test { def main(args: Array[String]) { val pt = new Point(10, 20); // 새 위치로 이동합니다 pt.move(10, 10); } }
위의 코드를 실행하면, 출력 결과는 다음과 같습니다:
$ scalac Test.scala $ scala Test x의 좌표점: 20 y의 좌표점: 30
Scala가 기본 클래스를 계승하는 것은 Java와 유사하지만, 다음 점에 유의해야 합니다:
1비추출 메서드를 재정의할 때는 override 접지자를 사용해야 합니다.
2기본 클래스의 생성자에 参数를 전달할 수 있는 것은 메인 생성자만입니다.
3자식 클래스에서 부모 클래스의 추출 메서드를 재정의할 때 override 키워드를 사용하지 않아도 됩니다.
다음 예제를 통해 살펴보겠습니다:
class Point(xc: Int, yc: Int) { var x: Int = xc var y: Int = yc def move(dx: Int, dy: Int) { x = x + dx y = y + dy println("x의 좌표점: " + x); println("y의 좌표점: " + y); } } class Location(override val xc: Int, override val yc: Int, val zc: Int) extends Point(xc, yc){ var z: Int = zc def move(dx: Int, dy: Int, dz: Int) { x = x + dx y = y + dy z = z + dz println("x coordinate point : "); + x); println("y coordinate point : "); + y); println("z의 좌표점: " + z); } }
Scala는 extends 키워드를 사용하여 클래스를 계승합니다. 예제에서 Location 클래스는 Point 클래스를 계승합니다. Point는 부모 클래스(기본 클래스)로, Location은 자식 클래스로 불립니다.
override val xc 부모 클래스의 필드를 재정의합니다.
계승은 부모 클래스의 모든 속성과 메서드를 계승합니다. Scala는 하나의 부모 클래스만 계승할 수 있습니다.
다음 예제와 같이:
import java.io._ class Point(val xc: Int, val yc: Int) { var x: Int = xc var y: Int = yc def move(dx: Int, dy: Int) { x = x + dx y = y + dy println("x coordinate point : "); + x); println("y coordinate point : "); + y); } } class Location(override val xc: Int, override val yc: Int, val zc: Int) extends Point(xc, yc){ var z: Int = zc def move(dx: Int, dy: Int, dz: Int) { x = x + dx y = y + dy z = z + dz println("x coordinate point : "); + x); println("y coordinate point : "); + y); println("z의 좌표점: " + z); } } object Test { def main(args: Array[String]) { val loc = new Location(10, 20, 15); // 새 위치로 이동합니다 loc.move(10, 10, 5); } }
위의 코드를 실행하면, 출력 결과는 다음과 같습니다:
$ scalac Test.scala $ scala Test x coordinate point : 20 y coordinate point : 30 z의 좌표점: 20
Scala를 통해 비추출 메서드를 다시 작성하려면 override 접지자를 사용해야 합니다.
class Person { var name = "" override def toString = getClass.getName + "[name=" + name + "]" } class Employee extends Person { var salary = 0.0 override def toString = super.toString + "[salary=" + salary + "]" } object Test extends App { val fred = new Employee fred.name = "Fred" fred.salary = 50000 println(fred) }
위의 코드를 실행하면, 출력 결과는 다음과 같습니다:
$ scalac Test.scala $ scala Test Employee[name=Fred][salary=50000.0]
In Scala, there is no such thing as static, but it also provides an implementation method for the singleton pattern, which is to use the keyword object.
In Scala, when using the singleton pattern, in addition to defining the class, you also need to define an object with the same name. The difference between the object is that the object cannot take parameters.
When a singleton object shares the same name with a class, it is called the companion object of this class: companion object. You must define both the class and its companion object in the same source file. The class is called the companion class of this singleton object: companion class. The class and its companion object can access each other's private members.
import java.io._ class Point(val xc: Int, val yc: Int) { var x: Int = xc var y: Int = yc def move(dx: Int, dy: Int) { x = x + dx y = y + dy } } object Test { def main(args: Array[String]) { val point = new Point(10, 20) printPoint def printPoint{ println("x coordinate point : "); + point.x); println("y coordinate point : "); + point.y); } } }
위의 코드를 실행하면, 출력 결과는 다음과 같습니다:
$ scalac Test.scala $ scala Test x coordinate point : 10 y coordinate point : 20
/* filename:Marker.scala * author:기본 튜토리얼 웹사이트 * url:ko.oldtoolbag.com */ // private constructor class 마커 private(val color: String) {}} println("색상 표시 생성" + this) override def toString(): String = "색상 표시:"+ color } // 컴퍼니 오브젝트, 클래스 이름과 동일하며, 클래스의 비공개 속성과 메서드에 접근할 수 있습니다 object 마커{ private val markers: Map[String, 마커] = Map( "빨간색" -> new 마커("빨간색"), "파란색" -> new 마커("파란색"), "緑색" -> new 마커("緑색") ) def apply(color: String) = { if(markers.contains(color)) markers(color) else null } def getMarker(color: String) = { if(markers.contains(color)) markers(color) else null } def main(args: Array[String]) { println(마커("빨간색")) // 싱글턴 함수 호출, 점(. 기호를 생략) println(마커 getMarker "파란색") } }
위의 코드를 실행하면, 출력 결과는 다음과 같습니다:
$ scalac 마커 마커.scala $ scala 마커 색상 표시: 빨간색 생성 색상 표시: 파란색 생성 색상 표시:緑색 생성 색상 표시: 빨간색 색상 표시: 파란색