스터디사이트 : https://www.hackerrank.com



JAVA Basic : 클래스와 인스턴스

: 입력된 나이 판별하기



1박2일동안 개발자교육을 함께한 반사람들과 함께 쫑파티(?) 등 뭐 겸사겸사 1박2일로 휴가를 갔다오느라 포스팅이 늦었다..

그 전 이틀은 목감기때메 고생하느라...

지금도 목이 맛이가서 사오정돼따 ㅋㅋ


그렇지만 그런 핑계를 알 리 없는 스터디사이트는 나에게 매일마다 꾸준히 과제를 떠먹여 주시고 계셨기때문에 좀 밀려있다...ㅋ


이번시간은 클래스와 인스턴스에 대한 기본코딩인데,

이렇게 된 김에 클래스와 인스턴스에 대한 개념을 제대로 짚고 넘어가야하지 않나 해서 검색을 좀 해봤다.


정리를 위해 웹서핑을 신나게하던 중 위키백과에 '객체 지향 프로그래밍' 문서를 발견했는데,

클래스와 인스턴스 등 개념적인 부분들이 잘 나와있는 것 같다..



객체지향 프로그래밍 - 위키백과

https://ko.wikipedia.org/wiki/%EA%B0%9D%EC%B2%B4_%EC%A7%80%ED%96%A5_%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D



클래스

: 같은 종류의 집단에 속하는 속성(attribute)과 행위(behavior)를 정의한 것


인스턴스

: 실제로 메모리상에 할당된 것

클래스가 인스턴스화 된 것을 객체라고 하는데, 이때 쓰이는 인스턴스가 이 인스턴스인 것이다.

'인스턴스화 된 것' 이란 뜻이 '메모리에 할당된 것'이라고 풀어 쓴다면,

" '클래스가 실제 메모리상에 할당된 것'객체라고 한다 " 라고 말할 수 있을 것이다.



객체 지향 프로그래밍-기본 구성 요소※ 객체 지향 프로그래밍의 기본 구성 요소 ( source by 위키백과 )





※ 주어진 코드



※ 생성자

  변수

initialAge, int

  조건

만약 클래스 생성자 입력값이 음수라면, "Age is not valid, setting age to 0" 을 출력할 것.

yearPasses() 메소드를 거치면 나이가 1씩 증가

amIOld() 메소드를 거치면 아래의 메시지를 출력 할 것.

13세 미만 - "You are young."

13세 이상 18세 미만 - "You are a teenager."

나머지 - "You are old."


이번 문제 설명 중 

" The code that creates each instance of your Person class is in the main method. " 라는 문구가 있는데 직역하면

The code that creates each instance of your Person class is ②in the main method.

① 너의 'Person' 클래스의 각 인스턴스를 만드는 코드 (인스턴스 = 실제로 메모리상에 할당된 것)

는 (is)

② 메인 메소드 안에

있다. (is)


이다... 이게 영어공부도 시켜주네 ㅋ



입력

4

-1

10

16

18


출력

Age is not valid, setting age to 0.

You are young.

You are young.


You are young.

You are a teenager.


You are a teenager.

You are old.


You are old.

You are old.


코딩 & 결과

단순 조건문을 쓰는걸로 끝났다..

public class Person {

    private int age;

  

public Person(int initialAge) {

  // Add some more code to run some checks on initialAge

        if(initialAge <0){

            this.age = 0;

            System.out.println("Age is not valid, setting age to 0.");

        }else{

            this.age=initialAge;

        }

}


public void amIOld() {

  // Write code determining if this person's age is old and print the correct statement:

        if(this.age<13){

            System.out.println("You are young.");

        }else if(this.age>=13 && this.age<18){

            System.out.println("You are a teenager.");

        }else{

            System.out.println("You are old.");

        }

}


public void yearPasses() {

  // Increment this person's age.

                this.age=this.age+1;

}

결과 : 

Age is not valid, setting age to 0.

You are young.

You are young.


You are young.

You are a teenager.


You are a teenager.

You are old.


You are old.

You are old.

+ Recent posts