Exercise: Bank Account
다음 속성(property)을 갖는 BankAccount 클래스를 만든다.
• Account number (계좌마다 서로 다른 값)
• Account holder name
• Balance (계좌 잔액)
BankAccount 클래스는 다음 메소드(method)를 갖는다.
• Deposit (입금)
• Withdraw (출금, 성공하면 true, 잔액이 모자라서 실패하면 false 리턴)
• balance 속성 setter는 private으로 하여 외부에서 사용 금지
아래 사용 예시의 코드가 동작하도록 한다.
팁
유일한 Account Number를 할당하기 위해, 새 BankAccount 객체가 생성될 때마다 값을 증가시키
는 카운트를 사용할 수 있다. 이 카운트는 companion object에 저장한다.
class BankAccount(val Name : String, var account : Double) {
companion object {
private var accountCount=10
}
val accountNumber:Int
init{
accountNumber=accountCount++
}
var balance:Double = account
fun deposit(money : Double) {
balance += money
}
fun withdraw(money : Double):String {
if (balance>=money){
balance-=money
return "true"
}
else
return "false"
}
}
fun main() {
val account = BankAccount("John Smith", 100.0)
println(account.accountNumber) // Output: 10
println(account.balance) // Output: 100.0
println(BankAccount("James Baker", 10.0).accountNumber) // Output: 11
// account.balance = 10
// Compile Error (Cannot assign to 'balance': the setter is private in 'BankAccount')
account.deposit(50.0)
println(account.balance) // Output: 150.0
val success = account.withdraw(75.0)
println(success) // Output: true
println(account.balance) // Output: 75.0
val failure = account.withdraw(100.0)
println(failure) // Output: false
println(account.balance) // Output: 75.0
}
※ balance 값에 직접 접근할 때 컴파일 에러가 발생되는 부분을 추가 작성할 필요가 있음.
Exercise: Vehicle Inheritance
여러 타입의 탈 것의 부모 클래스가 될 Vehicle 클래스를 만든다. Vehicle 클래스를 상속하여 Car,
Motorcycle, Bicycle 등을 만들 수 있다.
Vehicle 클래스는 다음 속성을 갖는다.
• make (제조사)
• model (모델명)
• year (생산년도)
Vehicle 클래스는 다음 메소드를 갖는다.
• start (출발)
• stop (정지)
Car, Motorcyle, Bicycle 클래스를 Vehicle 클래스를 상속하여 만든다.
Car 클래스는 다음의 추가 속성을 갖는다.
• numDoors (차문의 수)
Motorcycle 클래스는 다음의 추가 속성을 갖는다.
• hasSidecar (사이드카를 갖는지 여부를 나타내는 Boolean)
Bicycle 클래스는 다음의 추가 속성을 갖는다.
• numGears (기어 수)
각 서브클래스(Car, Motorcycle, Bicycle)는 자신의 start, stop 메소드를 갖는다. 예를 들어 Car의
start는 키를 돌린다, Bicycle의 start는 페달을 밟는다와 같이 만든다. 실제로 이런 내용을 만들 수
는 없으니 println으로 해당 동작을 출력하도록 한다.
open class Vehicle(val make:String, val model:String, val year:Int){
open fun start(){
println("start")
}
open fun stop(){
println("stop")
}
}
class Car(make:String, model:String, year:Int, val numDoors:Int):Vehicle(make, model, year) {
override fun start() {
println("Turning key in ignition")
}
override fun stop() {
println("Applying brakes and turning off engine")
}
}
class Motorcycle(make:String, model:String, year:Int, val hasSidecar:Boolean):Vehicle(make, model, year) {
override fun start() {
println("Kicking starter")
}
override fun stop() {
println("Applying brakes and turning off engine")
}
}
class Bicycle(make:String, model:String, year:Int, val numGears:Int):Vehicle(make, model, year) {
override fun start() {
println("Pedaling")
}
override fun stop() {
println("Applying brakes")
}
}
fun list_name(vehicles: List<Vehicle>) {
for (v in vehicles) {
println("${v.make} ${v.model} ${v.year}")
}
}
fun main() {
val car = Car("Hyundai", "Casper", 2022, 4)
val motorcycle = Motorcycle("Harley Davidson", "Fat Boy", 2022, true)
val bicycle = Bicycle("Samchuly", "Lucia", 2022, 7)
car.start() // Output: Turning key in ignition...
car.stop()
// Output: Applying brakes and turning off engine...
println(car.numDoors) // Output: 4
motorcycle.start() // Output: Kicking starter...
motorcycle.stop() // Output: Applying brakes and turning off engine...
println(motorcycle.hasSidecar) // Output: true
bicycle.start() // Output: Pedaling...
bicycle.stop() // Output: Applying brakes...
println(bicycle.numGears) // Output: 7
list_name(listOf(car, motorcycle, bicycle))
// Output:
// Hyundai Casper 2022
// Harley Davidson Fat Boy 2022
// Samchuly Lucia 2022
}
Exercise: Vector Addition
벡터 표현을 위한 Vector 클래스를 만들고 plus 연산자를 오버로딩한다.
Vector 클래스는 다음 속성을 갖는다.
• x (the x-coordinate of the vector)
• y (the y-coordinate of the vector)
Vector 클래스는 다음 메소드를 갖는다.
• toString (벡터를 문자열로 변환, 예를 들어 (x, y) 와 같은 형태로 만든다.)
• operator plus (두 벡터를 더한 결과를 리턴)
data class Vector(val x:Int, val y:Int) {
operator fun plus(other:Vector):Vector = Vector(x + other.x, y + other.y)
override fun toString(): String = "($x, $y)"
}
fun main(){
val v1 = Vector(1, 2)
val v2 = Vector(3, 4)
println(v1 + v2) // Output: (4, 6)
}
'Android > Kotlin' 카테고리의 다른 글
# 코틀린 기초 실습 1주차 (0) | 2024.03.12 |
---|