국비학원/공부

21일차 java(9)

mikan- 2023. 7. 3. 00:01

# 객체 자동형변환

public class ShapeTest {

	public static void main(String[] args) {
		System.out.println("객체자동형변환 연습");
		Shape s = new Shape();
		Point p = new Point();
		Line l = new Line();
		Square sq = new Square();
		
		s.shapeDraw();
		p.pointDraw();
		l.lineDraw();
		sq.squareDraw();
		
		System.out.println("== 객체 자동형변환 ==");
		
		Shape sh[] = new Shape[4]; // Shape형의 객체만 저장
		sh[0] = s;
		sh[1] = p; // 자식클래스의 객체 -> 자동으로 부모형으로 변환 -> 저장
		// sh[1] = new point(); // 익명개체
		// Shape s = new Point();
		sh[2] = l; // 부모형 < 자식형 -> 부모의 멤버, 메소드를 모두 가지고 있다
		sh[3] = sq; // 직원(부모) = 팀장(자식) (직원의기능(부모) + 팀장의기능(자식))
	
		for(int i = 0; i < sh.length; i++) {
			sh[i].draw(); // 메소드명은 같지만 객체가 다르기에 다른기능 구현
			whoAreYou(sh[i]);
		}
	}
	
	// 혈연관계
	// 형식) 객체명 instanceof 부모클래스명 = true(자식 OK), false(자식 X)
	static void whoAreYou(Shape sh) {
		// Shape 자손인지 확인
		if (sh instanceof Shape) {
			System.out.println("Shape인걸 확인 했습니다.");
			System.out.println("즉 Shape의 자손이 맞습니다.");
			
		} else {
			System.out.println("Shape가 아닌걸 확인 했습니다.");
		}
		
		// Point 자손인지 확인
		if (sh instanceof Point) {
			System.out.println("Point인걸 확인 했습니다.");
			System.out.println("즉 Shape의 자손이 맞습니다.");
		} else {
			System.out.println("Point가 아닌걸 확인 했습니다.");
		}
		
		// Line 자손인지 확인
		if (sh instanceof Line) {
			System.out.println("Line인걸 확인 했습니다.");
			System.out.println("즉 Shape의 자손이 맞습니다.");
		} else {
			System.out.println("Line가 아닌걸 확인 했습니다.");
		}
		
		// Square 자손인지 확인
		if (sh instanceof Square) {
			System.out.println("Square인걸 확인 했습니다.");
			System.out.println("즉 Shape의 자손이 맞습니다.");
		} else {
			System.out.println("Square가 아닌걸 확인 했습니다.");
		}	System.out.println("===============================");
	
	}
}

// 상속관계(Shape -> Point -> Line -> Square)
class Shape {
	
	// shape 에서만 사용하는 메소드
	void shapeDraw() {
		System.out.println("Shape");
	}
	
	// 모든 도형에 공통으로 사용하는 메소드
	void draw() {
		System.out.println("draw -> Shape");
	}
}

// 상속받은 자식 클래스 : Point(점)
// 상속의 조건은 is a 관계성립(draw, shapeDraw + pointDraw)
class Point extends Shape {
	void pointDraw() {
		System.out.println("Point");
	
	}
	
	// 오버라이딩
	void draw() {
		System.out.println("draw -> Point");
	}
}

// Line = 점(Point)들이 모이면 직선이됨
// Point 의 메소드(3개) + Line 메소드(1개)
class Line extends Point {
	
	void lineDraw() {
		System.out.println("lineDraw");
	}
	
	// 오버라이딩
	void draw() {
		System.out.println("draw -> line");
	}
}

// Square -> Line(4개) + 1개 -> 5개
// 다형성 : 같은 메소드를 호출 했을때 처리 결과가 다르다(문화차이)
class Square extends Line {
	void squareDraw() {
		System.out.println("squareDraw");
	}
	
	// 오버라이딩
	void draw() {
		System.out.println("draw -> squareDraw");
	}
}

 

# 자동형변환 (2)

/*
 * 객체형변환(자동, 명시적인 형변환)
 * 장점 : 메소드의 개수를 줄일 수 있고, 오버라이딩 개수 줄일수 있다.
 *        -> 코딩줄을 줄일 수 있다. -> 개발시간이 단축 -> 프로그램의 효율성 극대화
 */

class Employee { // 일반직원
	
	// 세금율 계산
	// Employee or Manager or Engineer
	// 메소드 통일 = 오버로딩
	public void taxRate(Employee e) {
		
		// 내부에서 부모, 자식 구분 -> 각각 구분
		if (e instanceof Manager) { // manager.taxRate(manager)
			Manager m = (Manager) e;
			System.out.println("Manager에 맞게 세금계산(1.0)" + m);
		} else if (e instanceof Engineer) {
			Engineer eng = (Engineer)e;
			System.out.println("Engineer에 맞게 세금계산(0.5)" + eng);
		} else if (e instanceof Employee) {
			System.out.println("Employee에 맞게 세금계산(0.3)" + e);
		}
		
	} // tax 0.3
	// public void taxRate(Manager m) {} // tax 1.5
	// public void taxRate(Engineer eg) {} // tax 0.5
}

// 팀장 : 팀장의 역활 + 일반직원(Employee)의 역활
class Manager extends Employee {
	
}

// 엔지니어 : 엔지니어의 역활 + 일반직원(Employee)의 역활
class Engineer extends Employee {
	
}

public class CastTest {

	public static void main(String[] args) {
		
		Employee emp = new Employee();
		Manager manager = new Manager();
		Engineer engin = new Engineer();
		
		// taxRate() 메소드를 하나로 통합함
		// 자식들도 부모의 메소드를 사용할 수 있음
		emp.taxRate(emp); // 부모
		manager.taxRate(manager); // 자식 -> 부모로 자동 형변환
		engin.taxRate(engin); // 자식 -> 부모로 자동 형변환
		
	}
}

 

 

# 예외처리 (1)

// 예외처리
public class HelloTest {

	public static void main(String[] args) {
		
		int i = 0; // 첨자
		String greetings[] = {"객체형변환", "예외처리", "예외처리방법"};
		while (i < 4) { // 3 < 4 논리적인 에러 발생
			System.out.println(greetings[i]); // 논리적인 에러
			i++;
		}
	}

}

 

# 예외처리 (2)

// 예외처리
public class HelloTest2 {

	public static void main(String[] args) {
		
		/* (1)
		int i = 0; // 첨자
		String greetings[] = {"객체형변환", "예외처리", "예외처리방법"};
		while (i < 3) {
			System.out.println(greetings[i]); // 논리적인 에러
			i++;
		}
		*/
		try {
			HelloTest2 ht = new HelloTest2();
			ht.go();
		} catch(ArrayIndexOutOfBoundsException e) {
			System.out.println("배열의 첨자계산이 잘못 되었습니다.");
			System.out.println(e.getMessage()); // 초간단 에러메세지
			System.out.println(e.toString()); // e.getMessage 보다 더 자세하게보여줌
			e.printStackTrace(); // 에러에 관련된 모든 클래스 추적해서 보여줌
			
		}
	}
	
	public void go() throws ArrayIndexOutOfBoundsException { // work
		
		int i = 0; // 첨자
		String greetings[] = {"객체형변환", "예외처리", "예외처리방법"};
		while (i < 4) {
			System.out.println(greetings[i]); // 논리적인 에러
			i++;
		}
	}
}

 

# 예외처리 (3)

public class ExceptionTotal {

	public static void main(String[] args) {
		System.out.println("매개변수 2개 전달해서 계산(동적배열)");
		try {
			// 숫자로 변환하는 이유 : 계산하기 위해서
			int a = Integer.parseInt(args[0]); // "9" -> 9
			int b = Integer.parseInt(args[1]); // "3" -> 9
			System.out.println("a : " + a + ", b : " + b);
			System.out.println("a를 b로 나눈 몫 : " + a / b);
		} catch (Exception e) { // 위의 처리하는 3개의 예외처리외의 다른 예외가 발생 했을때
			System.out.println(e);
			System.out.println("위의 예외처리외의 나머지를 처리해줍니다.");
		}/* catch (ArithmeticException e) {
			System.out.println(e); // e.toString()
			System.out.println("어떤 수 를 0으로 나눌수가 없음");
		} catch (IndexOutOfBoundsException | NumberFormatException e) {
			System.out.println(e);
			System.out.println("반드시 2개를 입력하거나 숫자만 입력가능함");
		} catch (NumberFormatException e) { // 숫자 대신에 문자를 입력할 경우
			System.out.println(e);
			System.out.println("반드시 숫자를 입력해야 합니다.");
		} catch (Exception e) { // 위의 처리하는 3개의 예외처리외의 다른 예외가 발생 했을때
								// Exception를 맨 앞에 적기가 가능하지만 나머지 기능은 사용이 안됨
			System.out.println(e);
			System.out.println("위의 예외처리외의 나머지를 처리해줍니다.");
		// 메모리에 저장된 데이터를 파일로 저장종료(DB연결해제)
		}*/ finally { 
			System.out.println("예외처리 발생유무 관계 없이 무조건 반드시 처리하겠음");
		}
	}
}

 

# 문자열 객체 (1)

public class StringTest {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		System.out.println("문자열을 입력하시오 : ");
		String input = sc.nextLine(); // next()(단어), nextLine()(문장)
		// System.out.println("input : " + input);
		stringPrint(input);
		sc.close(); // 메모리를 해제시켜주는 메소드(프로그램 종료와 함께)
	}
	
	// 매개변수O 반환값X
	public static void stringPrint(String s) {
		
		// 1. concat : 문자열 결합
		System.out.println("s.concat('test') : " + s.concat("test"));
		
		// 2. substring(시작인덱스 번호(O), 종료 인덱스 -1(바로 앞번호 까지)
		System.out.println("s.substring(1, 4) : " + s.substring(1, 4));
		
		// 3. 시작인덱스번호 부터 문자열 끝까지 출력
		System.out.println("s.substring(1) : " + s.substring(1));
		
		// 4. toUpperCase(대문자로 변환) <-> toLowerCase(소문자로 변환)
		System.out.println("s.toUpperCase(대문자로변환) : " + s.toUpperCase());
		System.out.println("s.toLowerCase(소문자로변환) : " + s.toLowerCase());
		
		// 5. replace : 특정문자열을 변경(변경전 단어 -> 변경후 단어)
		System.out.println("s.replace('l', 't') 만약에 l이 있으면 t로 바꾸기 : " + s.replace('l', 't'));
		
		// 6. legnth : 문자열의 길이 / 배열명.length : 배열의 길이(메소드X)
		System.out.println("s.length : " + s.length());
		
		// 7. charAt(인덱스번호) : 문자열 중에서 특정위치에 있는 문자 출력
		System.out.println("s.charAt(2) : " + s.charAt(2));
		
		// 8. indexOf('문자') : 특정문자가 앞에서부터 몇번째 인덱스번호에 위치 하는지
		// 못찾으면 -1을 리턴
		System.out.println("s.indexOf('l' : " + s.indexOf('l'));
		
		// 9. lastIndexOf() : 특정문자가 뒤에서부터 몇번째 인덱스번호에 위치 하는지
		System.out.println("s.lastIndexOf('l') : " + s.lastIndexOf('l'));
		
		// 10. trim() : 공백을 제거 ('ab cd' -> 'abcd')
		System.out.println("s.trim().length(공백을 제거 하고나서 문자열 길이) : " + s.trim().length());
	}
	
}

 

# 문자열객체 (2)

// 문자열 객체를 만드는 방법 2가지
public class StringTest2 {

	public static void main(String[] args) {
		
		// 1. String 문자열객체명 = "저장할 문자열";
		String str = "abc";
		
		// 저장할 문자열 존재확인O -> 새로운 공간에 안만들고 서로 연결시켜줌(주소값이 같음)
		String str2 = "abc"; // 내용, 주소 동일(같다)
		
		System.out.println("str 의 주소 : " + System.identityHashCode(str));
		System.out.println("str2 의 주소 : " + System.identityHashCode(str2));
		System.out.println("================================");
		
		// 2. new String("저장할 문자열")
		String str3 = new String("abc"); // 무조건 새로운 공간O
		String str4 = new String("abc"); // 주소는 다르지만 내용은 같다.
		
		System.out.println("str3 의 주소 : " + System.identityHashCode(str3));
		System.out.println("str4 의 주소 : " + System.identityHashCode(str4));
		System.out.println("================================");
		
		String str5 = new String("abcd");
		String str6 = new String("abcef"); // 내용이 다르면 주소값도 다름
		
		System.out.println("str5 의 주소 : " + System.identityHashCode(str5));
		System.out.println("str6 의 주소 : " + System.identityHashCode(str6));
		System.out.println("================================");
		
		// String (불변문자열) StringBuffer(가변문자열)
		// ex) String str = "abc" + "def" + "hij";
		//     String str = "abcdefhij"; -> String -> StringBuffer -> String
		//     String str = new StringBuffer("abc").append("def").append("hif").toString()
		
		// 객체 == 객체2 (주소비교)
		// 변수 == 변수 (내용비교)
		if (str == str2) {
			System.out.println("str1 과 str2는 주소가 서로 같다");
		} else {
			System.out.println("str1 과 str2는 주소가 서로 다르다");
		}
		
		if (str3 == str4) {
			System.out.println("str3 와 str4는 주소가 서로 같다");
		} else {
			System.out.println("str3 와 str4는 주소가 서로 다르다");
		}
		
		// 내용이 같은지 equals(), 대, 소문자를 구분해서 사용O
		//            contentEquals()도 가능(최신)
		
		if (str3.contentEquals(str4)) {
			System.out.println("str 3와 str4 의 내용은 같습니다.");
		} else {
			System.out.println("str 3와 str4 의 내용은 다릅니다.");
		}
	}
}

 

# 정적메소드 날짜 출력

// 오늘 날짜 출력 : Date, Calendar(정적메소드)
public class SimpleTest2 {

	public static void main(String[] args) {
		SimpleTest2 st = new SimpleTest2();
		Date d = st.getDate();
		System.out.println("d : " + d);
		
		st.setDate(d);
		
		// 한국 스타일에 맞게 출력시켜주는 클래스 : SimpleDateFormat
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// System.out.println("오늘 날짜 : " + sdf.format(d));
		
		SimpleDateFormat sdf = st.getSimpleDateFormat();
		st.setSimpleDateFormat(sdf, d);
		
		
		
		// Date d = new Date(); // 1. new 연산자
		// System.out.println("d : " + d); // d.toString() 자동으로 호출
	}
	
	public SimpleDateFormat getSimpleDateFormat() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf;
	}
	
	public void setSimpleDateFormat(SimpleDateFormat sdf2, Date d) {
		System.out.println("오늘 날짜 : " + sdf2.format(d));
	}
	
	// 1. 객체를 생성 해서 가져오는 경우 = 반환형을 통해서 객체를 얻어오는 경우(getXXX())
	// 형식) 접근지정자 반환형(객체형) getXXX() { return 생성한객체명; }
	public Date getDate() {
		/*
		Date d = new Date();
		return d;
		*/
		return new Date(); // 익명객체(이름이 없는 객체)
	}
	
	// 2. 만들어진 객체를 전달해서 대신 처리해주는 메소드
	// 형식) public void setXXX(전달 받을 클래스명 객체명(임의)) { 처리구문; }
	public void setDate(Date d1) {
		System.out.println("d1 : " + d1);
	}
}

'국비학원 > 공부' 카테고리의 다른 글

23일차 java(11)  (0) 2023.07.03
22일차 java(10)  (0) 2023.07.03
20일차 java(8)  (0) 2023.07.02
19일차 java(7)  (0) 2023.07.02
18일차 java(6)  (0) 2023.05.16