자바

JAVA STEP 25. CLASS&Constuctor

IT의 큰손 2023. 2. 17. 11:40
728x90

★ 사용자 편의를 위한 클래스 사용법

ex1) 요구사항 : 사람의 이름, 나이, 주소, 별명을 입력 받는 클래스

  • 소스코드
  • 설명
    • 클래스를 사용하는 사용자 입장에서, 배열문을 사용하여야 할때, 그 배열문에 대한 사항을 하나하나 다 입력을 하고, toString을 이용하여 출력을 하여야한다. 그러한 불편함을 제거하기위해 배열문에 자동적으로 add를 하여 배열문을 쌓고 출력과 동시에 배열문이 제거되도록 하였다.
package com.test.obj;

import java.util.Arrays;

public class Ex43_Class {

	public static void main(String[] args) {
		
//		Person p1 = new Person();
//		
//		p1.setName("홍길동");
//		p1.setAge(20);
//		p1.setAddress("서울시");
//		
//		String[] nick = { "멍멍이", "왈왈이", "쫑쫑이" };
//		
//		p1.setNick(nick);
//		
//		System.out.println(Arrays.toString(p1.getNick()));
//		
//		
//		Person p2 = new Person();
//		
//		p2.setName("아무개");
//		p2.setAge(30);
//		p2.setAddress("부산시");
//		
//		String[] nick2 = {"강아지", "고양이", "송아지", "병아리", "망아지"};
//		
//		p2.setNick(nick2);
		
		//위의 방식
		//1. Person 클래스 제작자	> 편함
		//2. Person 클래스 사용자	> 불편함
		
		//변경 방식
		//1. Person 클래스 제작자	> 불편함
		//2. Person 클래스 사용자	> 편함
		
		Person p1 = new Person();
		
		p1.setName("홍길동");
		p1.setAge(20);
		p1.setAddress("서울시");
		
		p1.addNick("멍멍이");
		p1.addNick("나옹이");
		p1.addNick("병아리");
		p1.addNick("송아지");
		p1.addNick("물고기");
		//p1.addNick("망아지");
		
		//System.out.println(Arrays.toString(p1.getNick()));
		
		System.out.println(p1.getNick());
		System.out.println(p1.getNick());
		System.out.println(p1.getNick());
		System.out.println(p1.getNick());
		System.out.println(p1.getNick());
		System.out.println(p1.getNick());
		
		p1.addNick("하하하");
		System.out.println(p1.getNick());
		
		
		

	}

}
ackage com.test.obj;

public class Person {

	private String name;		//이름
	private int age;			//나이
	private String address;		//주소
	//private String nick;		//별명(여러개 저장)
	
	//private String[] nick;
	//private String[] nick = new String[10];
	
	//private String[] nick = new String[5]; > 주소값을 참조하기 때문에 의미 없는 행위
	//private String[] nick;
	
	private String[] nick = new String [5];
	private int index = 0; //별명 배열의 방번호 제어
	
	//*******************************
		
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	//*******************************
		
	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	//*******************************
		
	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

//*******************************
	
//	public String[] getNick() {
//		return nick;
//	}

//	public void setNick(String[] nick) {
//		this.nick = nick;
//	}
	
	public void addNick(String nick) {
		
		if(this.index < this.nick.length) {
		
		this.nick[this.index] = nick;
		this.index++;
		
		}else {
			System.out.println("별명을 더 이상 추가 할 수 없습니다.");
		}

	}
	
	public String getNick() {
		
		//끝에서부터 하나씩 돌려주기
		if(this.index>0) {
			
		this.index—;
		String nick = this.nick[this.index];
		
		return nick;
		}else {
			System.out.println("더이상 별명이 없습니다.");
			return null;
		}
		
		
	}
	
	
}

 

ex2) 요구사항 : Calendar 함수를 이용한 클래스

  • 소스코드
  • 설명
    • 사용자 입장에서 직접 가입일자를 입력하려고 할 때, 해당 가입일자를 Calendar 함수를 직접 선언하고 사용을 하고, 출력 할 경우에도, %tF함수를 이용하여 출력을 해주어야하는 불편함이 있다. 이러한 불편함을 제거하기 위해 년도, 월, 일 만 입력을 받고, getter을 하였을 때, 자동적으로 출력 되도록 하였다.
package com.test.obj;

import java.util.Calendar;

public class Ex44_Class {

	public static void main(String[] args) {
		
//		Member hong = new Member();
//		
//		hong.setName("홍길동");
//		hong.setId("hong");
//		
//		Calendar regdate = Calendar.getInstance();
//		regdate.set(2023, 0, 10);
//		
//		hong.setRegdate(regdate);
//		
//		System.out.printf("%tF\n", hong.getRegdate());

		Member lee = new Member();
		
		lee.setName("이순신");
		lee.setId("lee");
		lee.setRegdate(2023, 1, 10);
		
		System.out.println(lee.getRegdate());
	}

}
package com.test.obj;

import java.util.Calendar;

public class Member {

	private String name;		//회원명
	private String id;			//회원 id
	
	private Calendar regdate; 	//가입 날짜

	//****************
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	//****************
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	//****************
	
//	public Calendar getRegdate() {
//		return regdate;
//	}
//
//	public void setRegdate(Calendar regdate) {
//		this.regdate = regdate;
//	}
	
	public void setRegdate(int year, int month, int date) {
		
		Calendar regdate = Calendar.getInstance();
		regdate.set(year, month-1, date);
		
		this.regdate = regdate;
		
	}
	
	public String getRegdate() {
		
		return String.format("%tF", this.regdate);
		
	}

 

ex3) 요구사항 : 이름, 부서, 직급, 관계를 입력 받는 클래스

  • 소스코드
  • 설명
    • 이름, 부서, 직급을 입력 받고, 사람들간의 관계를 나타낼 수 있도록 Superior이라는 변수를 선언해 주었는데, 이 멤버 변수의 자료형을 Employee로 선언해주어, 그 사람에 대한 복합적인 데이터가 들어갈 수 있도록 선언해 주었다.
package com.test.obj;

public class Ex45_Class {

	public static void main(String[] args) {
		
		Employee e1 = new Employee();
		
		e1.setName("홍길동");
		e1.setDeparment("영업부");
		e1.setPosition("과장");
		
		Employee e2 = new Employee();
		
		e2.setName("아무개");
		e2.setDeparment("영업부");
		e2.setPosition("대리");
		
		e2.setSuperior(e1);
		
		

	}

}
package com.test.obj;

public class Employee {
	
	//단일 데이터
	private String name;		//직원명
	private String position; 	//직급(사원,대리,과장,차장,부장...)
	private String deparment; 	//부서(영업부, 총무부, 인사부 ...)
	
	//복합 데이터
	private Employee superior; 	//상급자
	
	//*************************************
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	//*************************************
		
	public String getPosition() {
		return position;
	}

	public void setPosition(String position) {
		this.position = position;
	}

	//*************************************
		
	public String getDeparment() {
		return deparment;
	}

	public void setDeparment(String deparment) {
		this.deparment = deparment;
	}

	//*************************************
		
	public Employee getSuperior() {
		return superior;
	}

	public void setSuperior(Employee superior) {
		this.superior = superior;
	}
	
	
	
}

 

★ 생성자

  • 객체의 상태(멤버 변수)를 초기화하는 역할
  • 자료형 참조(객체)변수 = 객체 생성연산자 생성자;
  • 객체의 초기 상태를 개발자가 원하는대로 설정이 가능하다.
package com.test.obj.constructor;

public class Ex47_Constructor {

	public static void main(String[] args) {
		
		/*
		 
		 	생성자, Constructor + new
		 	- 객체의 상태(멤버 변수)를 초기화하는 역할
		 	
		 	자료형 참조(객체)변수 = 객체 생성연산자 생성자;
		 	Box box = new Box();
		 
		 */
		
		//*** 생성자 > 객체의 초기 상태를 개발자가 원하는대로 설정이 가능하다.
		// -> 같은 값으로 여러개의 사항들을 만들때 용이 할 것 같음.
		
		// 		 1    2
		//		new + Cup()
		Cup c1 = new Cup();
		
		//***** 역할 : 컵을 초기화한다.
		//c1.setColor("yellow");
		//c1.setSize(300);
		
		System.out.println(c1.getColor());
		System.out.println(c1.getSize());
		
		System.out.println(c1.info());
		
		Cup c2 = new Cup();
		
		c2.setColor("White");
		c2.setSize(500);
		
		System.out.println(c2.info());
		
		Cup c3 = new Cup("black");
		
		c3.setSize(600);
		
		System.out.println(c3.info());
		
		Cup c4 = new Cup(300);
		c4.setColor("green");
		System.out.println(c4.info());
		
		Cup c5 = new Cup("orange", 250);
		System.out.println(c5.info());
	}//main

}
package com.test.obj.constructor;

public class Student {

	private String name;
	private int kor;
	private int eng;
	private int math;
	
	/*
	 
	 - 개발자가 그 어떤 생성자도 만들지 않았을 경우에만 아래의 기본 생성자가 자동으로 만들어진다.
	 - 개발자가 명시적으로 생성자를 1개 이상 만들게 되면 아래의 기본 생성자는 자동으로 만들어지지 않는다.
	 	public Student() {
	 		
	 		this.name = null;
	 		this.kor = 0;
	 		this.eng = 0;
	 		this.math = 0;
	 
	 */
	
	//A 생성자가 할 수 있는 일은 B 생성자도 할 수 있다.
	//A 생성자가 할 수 있는 일은 C 생성자도 할 수 있다.
	//C 생성자가 할 수 있는 일은 B 생성자도 할 수 있다.
	
	//B > C > A
	
	//A.
	public Student() {
 		
// 		this.name = null;
// 		this.kor = 0;
// 		this.eng = 0;
// 		this.math = 0;
 		
 		//B 생성자를 호출한다.
 		this(null, 0, 0, 0);
	}
	
	//B.
	public Student(String name, int kor, int eng, int math) {
		
		//유효성 검사 > 값 대입(Setter의 역할과 동일)
		this.name = name;
		
		if(kor >=0 && kor <=100) {
			this.kor = kor;
		}
		if(eng >=0 && eng <=100) {
			this.eng = eng;
		}
		if(math >=0 && math <=100) {
		this.math = math;
		}
	}
	
	//C.
	public Student(int kor, int eng, int math) {
		
//		this.name = null;
//		
//		if(kor >=0 && kor <=100) {
//			this.kor = kor;
//		}
//		if(eng >=0 && eng <=100) {
//			this.eng = eng;
//		}
//		if(math >=0 && math <=100) {
//		this.math = math;
//		}
		
		//B 생성자를 호출한다.
		this(null, kor, eng, math);
	}
//**********************************8
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	//**********************************8
		
	public int getKor() {
		return kor;
	}
	public void setKor(int kor) {
		this.kor = kor;
	}

	//**********************************8
		
	public int getEng() {
		return eng;
	}
	public void setEng(int eng) {
		this.eng = eng;
	}

	//**********************************8
		
	public int getMath() {
		return math;
	}
	public void setMath(int math) {
		this.math = math;
	}
	
	//덤프 > 개발 때 도움이 많이 되는 메소드
	public String info() {
		
		return String.format("%s(%d,%d,%d)", this.name, this.kor, this.eng, this.math);
	}
	
}
728x90