오늘은 상속에 대해 배운다. 근데 속하고, 속해지고의 개념이 어려워서 일단 간단한 것부터 시작해봤다.
open class Coffee (val name : String) {
open fun type (){
println("$name is coffee")
}
}
class Americano(name : String) : Coffee(name) {
fun ingredient(){
println("${name}에는 2샷이 들어갑니다")
}
}
class Cafelatte(name : String) : Coffee(name){
fun price () {
println("${name}은 2천원입니다")
}
}
fun main () {
val americano = Americano("아메리카노")
val cafelatte = Cafelatte("카페라떼")
americano.type()
americano.ingredient()
cafelatte.type()
cafelatte.price()
}
이렇게 만들고나니 ingredient랑 price를 open class coffee로 올려서 함수처럼 쓰고싶어졌다!
그런데 선생님이 방금 말씀하셨는데 연습해보는거니까
하고 싶은걸 하지말고 그냥 연습이나 하는게 좋겠다.
override 연습해보자
fun main (){
var americano = Americano()
americano.name()
}
open class Coffee {
open fun name(){
println("It is coffee")
}
}
class Americano : Coffee() {
override fun name() {
println("It is americano")
}
}
override의 간단한 예제
부모클래스의 함수를 자식 클래스에 동일한 이름으로 덮어쓴 건가...
메시지 오버로드, 오버라이드! 객체지향의 다형성에 대해 알 수 있는 좋은 예제 감사합니다 (_ _)