티스토리 뷰

반응형

 

 

13일차 챌린지를 시작하자!

금일 tutorial은 이전의 소스코드를 재활용해

추상 메서드에 대해 배운다.

(+ 상속 내용 이어서 나옴.)

 

바로 소스코드를 보자.

 

먼저 Animal 클래스이다.

import org.w3c.dom.ls.LSOutput;

public abstract class Animal {
    private int age; // VS private int age;


    public Animal(int age) {
        this.age = age;
        System.out.println("An animal has been created!");
    }

    public abstract void eat();

    public void sleep() {
        System.out.println("An animal is sleeping.");
    }

    public int getAge() {
        return age;
    }

    public static void main(String[] args) {
        Dog d = new Dog();
        Cat c = new Cat();
        d.eat();
        c.eat();
        d.sleep();
        c.sleep();

        // Casting
        Object dog = new Dog();
        Dog realDog = (Dog) dog;
        realDog.ruff();

        Object str = "est";
        String realS = (String) str;
        realS.getBytes();

        // What happens when...
        Dog doggy = new Dog();
        if(doggy instanceof Animal) {
            Animal animal = (Animal) doggy;
            animal.sleep();
        }
        doggy.sleep();
    }
}

/*
ABSTRACT METHODS : DON'T HAVE A BODY

 */

 

 

다음으로 차례로 Dog, Cat 클래스이다.


public class Dog extends Animal {
    public Dog() {
        super(15);
        System.out.println("A dog has been created.");
    }
    public void eat() {
        System.out.println("A dog is eating.");
    }

//    public abstract eat();

    public void sleep() {
        System.out.println("A dog is sleeping");
    }

    public void ruff() {
        System.out.println("The dog says ruff");
    }

    public void run() {
        System.out.println("A dog is running");
    }
}

 

public class Cat extends Animal {
    public Cat() {
        super(7);
        System.out.println("A cat has been created");
    }

    public void eat() {
        System.out.println("A cat is eating.");
    }

    public void sleep() {
        System.out.println("A cat is sleeping.");
    }

    public void meow() {
        System.out.println("A cat meows!");
    }

    public void prance() {
        System.out.println("A cat is prancing");
    }
}

 

 

추상메서드를 생성하고 구현하는 내용인데

소스코드를 실행해서

출력결과를 하나씩 보면

딱히 어려움은 없을 것이다.

 

 


 

우린 바로

다음 포스팅에서 코드 리뷰로 만나자!

 

반응형