티스토리 뷰

Language/Java

Java - Class & 생성자

ShinyOcean 2021. 1. 28. 13:12

안녕하세요 Shiny Ocean입니다.

 

자바를 주제로한 두번째 포스팅은 Class와 생성자에 대하여 다루어 보겠습니다. 

 

클래스와 생성자는 자바 코딩에서 가장 기본적인 부분이며 중요한 부분입니다.

 

클래스는 유사한 특징을 갖는 객체들의 속성을 묶어놓은 그룹정도로 이해하시면 될것같습니다.

마치 C언어의 구조체와 비슷한 역할을 수행 합니다. 생성자는 객체가 생성될 때 객체의 초기화를

위해 실행되는 메소드입니다.

 

 

예제 문제를 해결하며 자세히 알아보겠습니다.

 

 

 

Java 예제문제 2 -클래스 설계하고 사용해보기

 

동물에 대한 정보를 생성자의 양식에 맞게 초기화하고 출력하는PG

조건1. 생성자를 만들어 데이터를 초기화한다.

조건2. Walk(); 얼마의 속도로 걷는다

조건3. Show); 정보를 출력한다

조건4. This. This();를 사용한다

 

 

 

해결 과정)

 

조건1. 생성자를 만들어 데이터를 초기화 한다

p.190 “생성자는 객체가 생성될 때 객체의 초기화를 위해 실행되는 메소드이다

저는 생성자는 정보를 저장할 때의 양식이라고 생각했습니다. 하나의 대상안에 들어있는 정보들을 형식에 맞춰 저장할수 있는 틀을 생성자라고 생각했습니다.

ex) 프로필 카드

위와 같이 프로그래머가 임의로 이름, 나이, 속도, 평균수명 순의 자료의 유형으로 입력을 받을수있게 만드는 하나의 정형화된 틀이라고 생각했습니다

 

이를 java code로 표현하면

public class BreathingOne 라는 클래스 내에

 

public BreathingOne(String name, double life, double speed, int age, boolean tail ) {

                                 this.name = name;

                                 this.life = life;

                                 this.speed = speed;

                                 this.tail = tail;

                                 this.age = age;

                 }

사용자임의로 원하는 변수타입과 초기화할값으로 양식을 만들어 초기화 합니다.

 

 

 

조건2. Walk();메소드를 만들어 얼마의 속도로 걷는지 출력 

저는 return값이 없이 출력을 하는 형식으로 코딩하였습니다.

Public void walk 메소드를 선언하고

출력문에 this.speed 출력되게 코딩하였습니다.

This this(); 조건 4에서 다루어 보겠습니다.

 

public void walk() {

                 System.out.println(this.name + "() " + this.speed + "km/h 걷는다");

}

 

 

 

조건3. Show(); 메소드를 만들어 생성자에 형식에 맞게 초기화된 값을 출력

Show()메소드는 기존에 초기화된 변수들을 출력하는 메소드로 tail변수(꼬리의 유무) 조건문을 통해

출력 되도록 코딩하였습니다.

 

public void show() {

 

                                 System.out.println("이름 : "+this.name);

                                 System.out.println("수명 : "+this.life);                     

                                 System.out.println("나이 : "+this.age);               

                                 if(this.tail==true) {

                                 System.out.println("꼬리가 있음 ");

                                 }

                                 else {

                                 System.out.println("꼬리가 없음 ");

                                 }

                 }

 

 

 

조건4. this();, this를 사용한다

 this레퍼런스는 단어 뜻 그대로 객체 자신을 가리키는 레퍼런스입니다.

This레퍼런스는 여러 메소드내에 동일한 이름의 매개변수의 사용을 메소드 내에서만 할수 있도록 해주는 레퍼런스라고 이해했습니다.

 

String name;    //이름

                 double life;  //평균수명 

                 double speed; //걷는속도 

                 boolean tail;  //꼬리가 있는애없는   walk 얼마의속도로 걷느

                 int age;

                

                 public BreathingOne(String name, double life, double speed, int age, boolean tail ) {

                                

                                 name = name;

                                 life = life;

                                 speed = speed;

                                 tail = tail;

                                 age = age;

                                

                 }

예를 들어 위의 코드에서 name, life, speed, age, tail 클래스내와 메소드 내에서 동일한 이름으로 사용되기 때문에 오류가 발생합니다. 그렇기 때문에

public BreathingOne(String name, double life, double speed, int age, boolean tail ) {

                                

                                 name = name;

                                 life = life;

                                 speed = speed;

                                 tail = tail;

                                 age = age;

                                

                 }

구문을 this 레퍼런스를 이용하여 객체 내에서만 사용할수 있도록

                 public BreathingOne(String name, double life, double speed, int age, boolean tail ) {

                                

                                 this.name = name;

                                 this.life = life;

                                 this.speed = speed;

                                 this.tail = tail;

                                 this.age = age;

                                

                 }

 

이렇게 수정했습니다.

마지막으로 this();는 오버로딩된 메소드내에서 생성자양식에 맞는 다른 메소드를호출할때 사용합니다.

 

                 public BreathingOne(String name, double life, double speed, int age ) {

                                

                                 this(name, life, speed, age,false);

                                

                 }

에서 꼬리의 유무를 나타내는 변수값인 Boolean tail의 값이 없을 경우 나머지 내게의 매개변수(name,life,age,false)는 그대로 받아들이고 tail값을 false로 하여 매소드를 호출하도록

This();안에 코딩하였습니다.

 

 

 

 

 

전체 코드)

public class BreathingOne {

                 String name;    //이름

                 double life;  //평균수명 

                 double speed; //걷는속도 

                 boolean tail;  //꼬리가 있는애없는   walk 얼마의속도로 걷느

                 int age;

                

                 public BreathingOne(String name, double life, double speed, int age ) {

                                

                                 this(name, life, speed, age,false);

                                

                 }  

                 public BreathingOne(String name, double life, double speed, int age, boolean tail ) {

                                

                                 this.name = name;

                                 this.life = life;

                                 this.speed = speed;

                                 this.tail = tail;

                                 this.age = age;

                                

                 }

                 public void walk() {

                                 System.out.println(this.name + "() " + this.speed + "km/h 걷는다");

                 }

                 public double setSpeed(double a) {

                

                                 this.speed =a;

                                

                                 return this.speed;

                 }

                 public void setLife(double b) {

                                 this.life = b;

                 }

                 public void setage(int c) {

                                 this.age = c;

                 }

                 public void show() {

                                 System.out.println("이름 : "+this.name);

                                 System.out.println("수명 : "+this.life);                     

                                 System.out.println("나이 : "+this.age);

                                 if(this.tail==true) {

                                 System.out.println("꼬리가 있음 ");

                                 }

                                

                                 else {

                                 System.out.println("꼬리가 없음 ");

                                 }

                                

                 }

} =========================main======================================

package ch04;

public class BreathingOneMain {       

                 public static void main(String[] args) {

                                 BreathingOne human = new BreathingOne("사람",80.3,5.0,23);

                                 human.show();

                                 human.walk();

                                 System.out.println();

                                 BreathingOne lion= new BreathingOne("사자",13.3,24.2,5,true);

                                 lion.show();

                                 lion.walk();

                                 System.out.println();

                                 BreathingOne  cat = new BreathingOne("고양이",15.4,30.2,7,true

                                                                   );

                                 cat.show();

                                 cat.walk();

                                 System.out.println();

                

                 }

 

}

 

결과 콘솔)

 

 

'Language > Java' 카테고리의 다른 글

Java - 간단한 끝말잇기 텍스트게임 구현  (1) 2021.01.28
Java - Abstract Class, 추상클래스  (0) 2021.01.28
Java - Array & Exception처리  (0) 2021.01.28
Java - Basic  (1) 2021.01.28
Java - intro  (0) 2021.01.28
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함