Java - 다형성, 상속, 예외

|

 


class Mother{
	String name;
	String job;
	int age;
	private Child[] childs;
	
	public Mother(String name, int age) {
		this.name = name;
		this.age = age;
	}
	public Mother(String name, int age, String job, Child[] childs) {
		this.name = name;
		this.age = age;
		this.job = job;
		this.childs = childs;
	}
	
	void goToSchool(String name, Child[] childs) {
		for(int i=0; i<=2; i++) {
			System.out.println(name + "는 " + childs[i].name + "과 학교를 갔다");
		}
	}
	
	void callChild(String name, Child[] childs) {
		for(int i=0; i<=2; i++) {
			System.out.println(name + "는 " + childs[i].name + "를 불렀다.");
		}
	}
	
	void setChild(Child[] childs) { //get 뒤에는 얻어가고자 하는 속성을 넣음.
		this.childs = childs; //주소값을 던진다.
	}
}

class Child{
	String name, hobby;
	int age;
	
	public Child(String name, int age) {
		this.name = name;
		this.age = age;
	}
	public Child(String name, int age, String hobby) {
		this.name = name;
		this.age = age;
		this.hobby = hobby;
	}
	
	String goToSchool(String name) {
		return name + "은 학교를 갔습니다";
	}
	void fight(Child c) {
		System.out.println(c.name + "와(과) 싸웠습니다.");
	}
}

public class 실습4일차 {


	public static void main(String[] args) {
		
/*
		•실습1: Mother에 대한 클래스
		- 속성:(String)name, (int)age, (String)job, private(Child[])childs
		- 생성자
		  Mother(String name, int age)
		  Mother(String name, int age, String job, Child[] childs)
		- 메소드:
		  void goToSchool(): ‘아이들과 학교가다’ 출력
		  void callChild(): 아이들 수만큼 출력 =>‘아이이름’이지금 갑니다
		  void setChild(Child[] c): 아이를 설정
		Mother의 goToSchool, setChild후 callChild 를 호출해 보기

		• Child에 대한 클래스
		- 속성:(String)name, (int)age, String hobby
		- 생성자
		  Child(String name, int age)
		  Child(String name, int age, String hobby)
		- 메소드:
		  void goToSchool(): ‘학교가다’ 출력
		  void fight(Child c): ‘아이이름’과 싸웠습니다 출력
		---------------------------------------------------------
*/

		Child[] c = new Child[3];
		c[0] = new Child("홍길동", 11);
		c[1] = new Child("임꺽정", 12);
		c[2] = new Child("이순신", 13);
		
		Mother mt = new Mother("영희", 35, "개발자", c);
		mt.goToSchool("영희", c); // name + "는 " + childs[i].name + "과 학교를 갔다" 배열별로 출력
		mt.setChild(c);
		mt.callChild("영희", c); // name + "는 " + childs[i].name + "를 불렀다." 배열별로 출력
		
		Child ch = new Child("홍길동", 11, "축구");
		System.out.println(ch.goToSchool("영희")); // 영희은 학교를 갔습니다
		ch.fight(ch); // 홍길동와(과) 싸웠습니다.
		
		
		
		
		
		
		

	}

}

--------------------------------------------------------------------------
class Book{
	int number;
	String title;
	String author;
	public void getLateFee(int day) {
	}
	
	public Book(int number, String title, String author) {
		this.number = number;
		this.title = title;
		this.author = author;
	}
	
	void getMethod() {
	}

	void setMethod() {
	}
	
	public boolean equals(Object obj) { //object에 대해서 재정의됨.
		if(obj!=null && obj instanceof Book) { //obj가 Person2의 Instance , "obj가 널이 아니고 && obj가 person2의 인스턴스가 맞냐?"
			return number ==((Book)obj).number; // "s1의 id와 파라미터로 넘어온 obj의 id가 같냐?" 값이 같은지 비교하는 equals? object?로 재정의됨. ()는 타입변환용임. Person2로 변환하지 않으면 id를 호출하지 못하므로.
		} else {
			return false;
		}
	}
	
}

class Animation extends Book{
	
	public Animation(int number, String title, String author) {
		super(number, title, author);
	}

	public void getLateFee(int day) {
		System.out.println(day*300);
	}
}

class Science extends Book{
	
	public Science(int number, String title, String author) {
		super(number, title, author);
	}

	public void getLateFee(int day) {
		System.out.println(day*200);
	}
}

public class 실습4일차2번 {

	public static void main(String[] args) {
		
		/*
		l 실습 2
		책을 대여해주는 업체를 위한 Book이라는 클래스를 작성한다
		Book는 관리자번호(number), 제목(title), 저자(author)를필드로 가진다
		Book클래스는 접근자(GetMethod)와 설정자(SetMethod)를 가진다.
		"Object클래스의 equals() 메소드를 재정의 해서 관리자 번호가 동일하면 동일한 책으로 간주한다."
		Book으로부터 상속받은 Animation,Science 클래스를 작성한다
		이들 클래스는 연체된 날짜에 따라서 연체료를 계산하는 getLateFee()메소드를
		재정의한다. 연체료는Animation은 300원/일,Science는 200원/일 이다
		클래스 Book, Animation, Science를 작성하라
*/

		Book bk = new Book(77, "죽은시인의 사회", "톰슐먼");
		Book bk2 = new Book(77, "난쏘공", "조세희");
		System.out.println(bk.equals(bk2)); //true
		
		Animation ani = new Animation(3, "마음의 소리", "조석");
		ani.getLateFee(3);
		
		Science sci = new Science(3, "Java의 정석", "남궁성");
		sci.getLateFee(3);
		
		System.out.println(ani.equals(sci)); //true
		System.out.println(ani.equals(bk)); //false
	}

}
--------------------------------------------------------------------------

package Week01;

abstract class Calculator{
	int left, right;
	public void setOprands(int left, int right) {
		this.left = left;
		this.right = right;
	}
	int _sum(){
		return this.left + this.right;
	}
	public abstract void sum();
	public abstract void avg();
	public void run() {
		sum();
		avg();
	}
}

class CalculatorDecoPlus extends Calculator{
	public void sum() {
		System.out.println("+sum :"+_sum());
	}
	public void avg() {
		System.out.println("+avg :"+(this.left+this.right)/2);
	}
}

class CalculatorDecoMinus extends Calculator{
	public void sum() {
		System.out.println("-sum :" +_sum());
	} 
	public void avg() {
		System.out.println("-avg :" +(this.left+this.right)/2);
	}
}

public class 다형성예제 {
	
	public static void execute(Calculator cal) {
		System.out.println("실행결과");
		cal.run();
	}

	public static void main(String[] args) {
		Calculator c1 = new CalculatorDecoPlus();
		c1.setOprands(10, 20);

		Calculator c2 = new CalculatorDecoMinus();
		c2.setOprands(10, 20);
		
		execute(c1);
		execute(c2);
	}

}
--------------------------------------------------------------------------

package Week01;

class Calculator1{
	int left, right;
	
	public void setOprands(int left, int right) {
		this.left = left;
		this.right = right;
	}
	
	public void sum() {
		System.out.println(this.left + this.right);
	}
	
	public void avg() {
		System.out.println((this.left + this.right)/2);
	}
}

class SubstractionableCalculator extends Calculator1{
	public void substract() {
		System.out.println(this.left - this.right);
	}
}

public class 상속예제 {

	public static void main(String[] args) {
		
		SubstractionableCalculator c1 = new SubstractionableCalculator();
		c1.setOprands(10, 20);
		c1.sum();
		c1.avg();
		c1.substract();

	}

}
--------------------------------------------------------------------------

package Week01;

public class 클래스예제 {

	public static void main(String[] args) {
		Song s = new Song("Dancing Queen",
				"ABBA",
				"Arrival",
				new String[] {"Benny Andersson", "Bjorn Ulvaeus", "프레디 머큐리", "윤종신"}, //String [] s = new String[] 
																						 // Song s = new Song[] 두줄을 한줄로 만든셈.
				1977,
				2);
		s.show();
	}
}

class Song{
	private String title;
	private String artist;
	private String album;
	private String[] composer;
	private int year;
	private int track;
	Song(String title, String artist, String album, String[] composer, int year, int track){
		this.title = title;
		this.artist = artist;
		this.album = album;
		this.composer = composer;
		this.year = year;
		this.track = track;
	}
	public void show() {
		System.out.println("노래 제목 : " + title);
		System.out.println("가수 : " + artist);
		System.out.println("앨범 : " + album);
		System.out.println("작곡가 : ");
		for(int i=0; i<composer.length; i++) {
			System.out.println(composer[i]);
			if(i+1 ==composer.length)
				System.out.println();
			else
				System.out.println(",");
		}
		System.out.println("년도 : " + year);
		System.out.println("트랙 번호 : " + track);
	}
}

--------------------------------------
/* 예외 */
1. 예외처리 예약어
- throw : 예외강제발생, 메소드안에서 쓰임, 의도적으로 예외를 발생시킴
- throws : 예외전가, 메소드에 달아서 책임을 전가시킴, 다음으로 넘겨버리는 것
- try ~(예외발생지역)~ catch ~(예외발생시 처리할 내용)~ finally ~ (예외발생유무와 상관없이 처리할 내용)~
2. Checked Exception : 컴파일시 예외처리 강제(무조건 try ~ catch 해야함) -> 대부분 프로그램으로 해결불가능
- throwable, exception, IOException, InterruptException
3. UnChecked Exception : 컴파일시 예외처리 선택(try ~ catch 안해도 됨) -> 대부분 프로그램으로 해결가능
- Error, ClassCastException, RuntimeException, NullPointException
4. printStackTrace() : 예외발생 당시의 call stack에 있었던 메소드의 정보와 예외 메세지를 출력(디버깅시 유용)
-> 로그가 굉장히 길어짐(개발시 대부분 이거 사용)
5. getMessage() : 발생한 예외 클래스의 인스턴스에 저장된 메세지를 리턴
-> 간단 명료

package Week01;

public class 예외처리예제1 {

	public static void main(String[] args) {
		System.out.println(1);
		System.out.println(2);
		try {
			System.out.println(3);
			System.out.println(0/0); //에러가 나서 catch블록으로 넘어감
			System.out.println(4); //실행되지 않는다.
		} catch (ArithmeticException ae) {
		if(ae instanceof ArithmeticException) //ae 객체가 예외가 맞느냐?
			System.out.println("true");
			System.out.println("ArithmeticException");
		} catch (Exception e) {
			System.out.println("Exception");
		} //try ~ catch 의 끝
		System.out.println(6);
	} //main 메소드의 끝

}
-------------------------------------------
package Week01;

public class 예외처리예제2 {

	public static void main(String[] args) {
		System.out.println(1);
		System.out.println(2);
		try {
			System.out.println(3);
			System.out.println(0/0); //예외발생!!
			System.out.println(4); //실행되지 않는다.
		} catch(ArithmeticException ae) {
			ae.printStackTrace(); //예외메세지 전부를 출력
			System.out.println("예외메시지 : " + ae.getMessage()); //간단명료 출력.
		} //try~ catch의 끝
		System.out.println(6);
	} //main 메소드의 끝

}
--------------------------------------------------------------------------

package Week01;

public class 예외처리예제3 {

	public static void main(String[] args) {
		try{
			Exception e = new Exception("고의로 발생시켰음.");
			throw e; //예외를 발생시킴
			//throw new Exception("고의로 발생시켰음.")
		} catch(Exception e) {
			System.out.println("에러 메세지 : " + e.getMessage());
			e.printStackTrace();
		}
		System.out.println("프로그램이 정상 종료되었음.");
	}

}
--------------------------------------------------------------------------

package Week01;

public class 예외처리예제4 {

	public static void main(String[] args) {
		//method1()은 static 메소드이므로 인스턴스 생성없이 직접 호출
		예외처리예제4.method1();
		System.out.println("method1()의 수행을 마치고 main메소드로 리턴.");
	} //main 메소드의 끝
	
	static void method1() {
		try {
			System.out.println("method1()이 호출되었습니다.");
			return; //현재 실행 중인 메소드를 종료한다.
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			System.out.println("method1()의 finally블럭이 실행되었습니다.");
		}
	} // method1 메소드의 끝

}
--------------------------------------------------------------------------
package Week01.exception;

import java.io.PrintStream;
import java.io.PrintWriter;

class MyException extends Exception{
	private String message;
	private Throwable cause;
	public MyException() {
		super();
	}
	
	public MyException(String msg) {
		super(msg);
		message = msg;
	}
	
	public MyException(Throwable cause) {
		super(cause);
		this.cause = cause;
	}
	
	public MyException(String msg, Throwable cause) {
		super(msg, cause);
		message = msg;
		this.cause = cause;
	}
	
	public void setCause(Throwable cause) {
		this.cause = cause;
	}
	
	public Throwable getCause() {
		return cause;
	}
	
	public void setMessage(String message) {
		this.message = message;
	}
	
	public String getMessage() {
		return message;
	}
	
	public void printStackTrace() {
		System.out.println(":: ERROR 발생!! ::");
		System.out.println("에러사유 = " + message);
		System.out.println("관련 클래스= " + cause);
		System.out.println(":: ERROR 출력끝!! ::");
		super.printStackTrace(System.out);
	}
	
	public void printStackTrace(PrintStream out) {
		super.printStackTrace(out);
	}
	
	public void printStackTrace(PrintWriter out) {
		super.printStackTrace(out);
	}
	
}

public class ExceptionTest {

	public static void main(String[] args) throws Exception {
		
			int x = 100;
			int y = 0;
			int tot = 0;
			try {
				tot = x / y;
			} catch(ArithmeticException ae) {
				MyException me = new MyException("나눗셈", ae);
				//throw me;
				me.printStackTrace();
			}
			System.out.println("tot = " + tot);
	}

}



-----------------------------------------------------------

package Week01;

public class MathTest {

	public static void main(String[] args) {
		
		//Math 메소드
		//Math내 모든 메소드는 static이고 2개의 상수가 존재
		//public static final double E = 2.17...;
		//public static final double PI = 3.1415...;
		
		//1.static double abs(double a)
		//float, int, long : 절대값 반환
		int l = Math.abs(-10);
		double d = Math.abs(-10.0);
		System.out.println(l); // 10
		System.out.println(d); // 10.0
		
		//2. static double ceil(double a)
		//주어진 값을 올림하여 반환한다.
		double d2 = Math.ceil(10.1);
		double d3 = Math.ceil(-10.1);
		double d4 = Math.ceil(10.000015);
		System.out.println(d2); // 11.0
		System.out.println(d3); //-10.0
		System.out.println(d4); // 11.0
		
		//3. static double max(double a, double d)
		//float, int, long
		//주어진 두 값을 비교하여 큰 쪽을 반환
		double d5 = Math.max(9.5, 9.50001);
		int i = Math.max(0, -1);
		System.out.println(d5); // 9.50001
		System.out.println(i); // 0
		
		//4. static double min(double a, double b)
		//float, int, long
		//주어진 두 값을 비교하여 작은쪽을 반환
		double d6 = Math.min(9.5, 9.50001);
		int i2 = Math.min(0, -1);
		System.out.println(d6); // 9.5
		System.out.println(i2); // -1
		
		//5. static double random()
		// 0.0 ~1.0 범위의 임의의 double 반환
		double d7 = Math.random();
		int i3 = (int)(Math.random()*10)+1;
		System.out.println(d7); // 0.0<=d<1.0
		System.out.println(i3); // 1<=i<=11
		
		//6. static double rint(double a) -> 안쓰임..................
		//주어진 double값과 가장 가까운 정수값을 double형으로 반환한다.
		double d8 = Math.rint(5.5); //
		double d9 = Math.rint(5.1);
		double d10 = Math.rint(-5.5);
		double d11 = Math.rint(-5.1);
		System.out.println(d8); //6.0
		System.out.println(d9); //5.0
		System.out.println(d10); //-6.0
		System.out.println(d11); //-5.0
		
		//7. static long round(double a)
		//	 static long round(float a)
		// 소수점 첫째자리에서 반올림한 long값을 반환
		long l2 = Math.round(5.5);
		long l3 = Math.round(5.11);
		long l4 = Math.round(-5.5);
		long l5 = Math.round(-5.1);
		double d12 = 90.7552;
		double d13 = Math.round(d12*100)/100.0;
		System.out.println(l2); // 6
		System.out.println(l3); // 5
		System.out.println(l4); // -5 
		System.out.println(l5); // -5
		System.out.println(d13); // 90.76
	

	}

}

--------------------------------------------------------------------------
package Week01;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class Lotto {

	public static void main(String[] args) {
		
		Lotto lotto = new Lotto();
		Scanner sc = new Scanner(System.in);
		
		System.out.println("로또 번호 추출 개수 입력 : ");
		int gameCnt = sc.nextInt();
		
		for(int i = 1; i<=gameCnt; i++) {
			System.out.println(i + "번째 로또번호 : " + lotto.lottoNumbers());
		}
	}
	
	String lottoNumbers() {
		List<Integer> lottoNum = new ArrayList<Integer>();
		
		//List 안에 로또번호 추가
		for(int i = 1; i<=45; i++) {
			lottoNum.add(i);
		}
		
		//set안의 수를 무작위로 섞는다
		Collections.shuffle(lottoNum);
		
		int[] lottoNums = new int[6];
		for(int i=0; i<6; i++) {
			lottoNums[i] = lottoNum.get(i);
		}
		
		//정렬
		Arrays.sort(lottoNums);
		
		return Arrays.toString(lottoNums);
			
	}

}

--------------------------------------------------------------------------
package Week01.poly2;

class Vet{ // 수의사
	public void giveShot(Animal a) { // 주사를 놓는다.
		a.makeNoise(); // 동물마다 다른 비명소리를 지른다.
	}
}

class Animal{
	// 각 동물은 이 메소드를 Overriding한다.
	public void makeNoise() {}
}

class Dog extends Animal{
	public void makeNoise() {
		System.out.println("멍멍");
	}
}

class Cat extends Animal{
	public void makeNoise() {
		System.out.println("야옹");
	}
}

public class PetOwner {

	public static void main(String[] args) {
		Vet v = new Vet();
		Dog d = new Dog(); // Animal의 하위 클래스
		Cat c = new Cat(); // Animal의 하위 클래스
		v.giveShot(d);
		v.giveShot(c);
	}

}
package Week01.poly2;

class Vet{ // 수의사
	public void giveShot(Animal a) { // 주사를 놓는다.
		a.makeNoise(); // 동물마다 다른 비명소리를 지른다.
	}
}

class Animal{
	// 각 동물은 이 메소드를 Overriding한다.
	public void makeNoise() {}
}

class Dog extends Animal{
	public void makeNoise() {
		System.out.println("멍멍");
	}
}

class Cat extends Animal{
	public void makeNoise() {
		System.out.println("야옹");
	}
}

public class PetOwner {

	public static void main(String[] args) {
		Vet v = new Vet();
		Dog d = new Dog(); // Animal의 하위 클래스
		Cat c = new Cat(); // Animal의 하위 클래스
		v.giveShot(d);
		v.giveShot(c);
	}

}
--------------------------------------------------------------------------

package Week01.poly1;

//다형성 p.64쪽

class Dog extends Animal{

	static String dog;

	public Dog(String dog) {
		this.dog = dog;
	}
	
}

class Cat extends Animal{

	static String cat;
	
	public Cat(String cat) {
		this.cat = cat;
	}
	
}

class Wolf extends Animal{

	static String wolf;
	
	public Wolf(String wolf) {
		this.wolf = wolf;
	}
	
}

public class Animal{

	public static void main(String[] args) {
		
		Animal[] animals = new Animal[3];
		animals[0] = new Dog("진돗개");
		animals[1] = new Cat("페르시안고양이");
		animals[2] = new Wolf("울버린");
		
		//각 객체별 재정의된 메소드가 실행된다.
		for(int i = 0; i<animals.length; i++) {
			animals[i].eat();
			animals[i].roam();
		}

	}

	private void roam() {
		System.out.println(Dog.dog + "가 으르렁댑니다.");
	}

	private void eat() {
		System.out.println(Cat.cat + "가 냠냠 먹습니다.");
	}

}

And