본문 바로가기

공부/자바 OOP

6월4일 - 상속 + 객체지향(다향성, object) + exception

교재 : 교학사 7장

 

상속

super -> 부모, 조상  /  this -> 나

- super        : 자식클래스에서 부모클래스 멤버변수에 접근할 때 

- super()      : 자식클래스의 생성자함수가 부모클래스의 생성자함수를 호출할 때

- this           : 멤버변수 (field)와 지역변수 구분하기 위해 

- this()         : 자신의 생성자 함수를 호출할 때

- 부모클래스 :

- 다형성   

- object

 

*가장 협소적인 정보, 지역정보가 가장 우선순위이다. 

 

상속관게에서 생성자 함수 호출 순서 

부모()-> 자신()

먼저 부모를 부르고 난 다음 그 안에 속해있는 자신의 함수를 호출해야하기 때문

 

package oop0604;

class School {
	String name="학교";
	public School(){
		System.out.println("School()...");
	}
}//class end

class MiddleSchool extends School { //school 상속
	String name="중학교"; //지역정보가 가장 우선순위이다
	public MiddleSchool(){
		//부모생성자함수를 호출하는 것이 생략되어져있다
		//부모생성자함수 호출 명령어
		super(); //생략가능
		System.out.println("MiddleSchool()..."); //부모를 부르고 나서 나를 불러야하기 때문에 
		                                                        //부모생성자함수 호출이 생략되어져 있다.
	}
}//class end

class HighSchool extends School { //부모 School
                                                 //자식 HighSchool
	String name="고등학교"; //field 멤버변수
	public HighSchool() {
		super(); //부모 생성자함수 호출명령어 , 생략가능
	} 
	public void disp(){ //method 멤버함수
		String name="종로고등학교"; //지역변수
		System.out.println(name);          //종로고등학교
		System.out.println(this.name);    //고등학교
		System.out.println(super.name); //학교
	}	
}//class end


public class Test01_Super {

	public static void main(String[] args) {
		// super
		
		//상속관계에서 생성자함수 호출순서
		//부모 -> 자신
		//School()-> MiddleSchool()
		MiddleSchool ms=new MiddleSchool();
		//자신의 멤버변수의 우선순위가 높다.
		System.out.println(ms.name); //중학교, 내 함수에 넣었기때문에 중학교로 나옴
		
		HighSchool hs=new HighSchool();
		//System.out.println(hs.name); //학교, 부모의 함수밖에 존재하지않기 때문에 부모의 값이 나옴
		hs.disp();
		
	}//main() end
}//class end

SUPER

- 부모클래스

package oop0604;

class Parent{
	int one;
	int two;
	public Parent() {}
	public Parent(int one, int two) {
		this.one = one;
		this.two = two;
	}	
}//class end

class Child extends Parent {
	int three;
	public Child() {
		//super(); 생략되어있음
	}
	public Child(int a, int b, int c){
		super(a,b); //부모의 초기값을 자식이 물려받을 때 super( , )로 해서 받는다
		//super.one=a;  super(a,b)와 같은 의미
		//super.two=b;
		three=c;
	}
}//class end

public class Test02_Super {

	public static void main(String[] args) {
		// 부모클래스 super
		
		Child child=new Child(10, 20, 30);
		System.out.println(child.one);    //10
		System.out.println(child.two);    //20
		System.out.println(child.three);  //30	
        
	}//main() end
}//class end

 

Polymorphism 다형

상속관계에서의 다형성을 점검해보는 것 . 형변환

부모클래스 입장에서 형태가 여러가지이다.

클래스들간의 형변환을 위해서 

 

1) 일반적인 방식의 객체 생성

- new연산자를 사용

- POJO(Plain Old Java Object) 방식

package oop0604;

class Father {
	public String name="아버지"; //field
	public String addr="주소";
	
	public Father() {} //constructor
	public Father(String name, String addr) {
		this.name = name;
		this.addr = addr;
	}
	public void disp(){ //method
		System.out.println(this.name);
		System.out.println(this.addr);
	}	
}//class end

class Son extends Father {
	public Son(){}
	public Son(String n, String a){
		super.name=n; //개별접근 & 생성자함수 접근 방법과 같은 것임 
		super.addr=a;
	}
}//class end

class Daughter extends Father {
	public Daughter(){}
	public Daughter(String name, String addr){  //변수는 최대한 지역변수그대로 가는게 안헷갈림
		super(name,addr); //생성자함수 접근
	}
}//class end

public class Test03_Polymorphism {

	public static void main(String[] args) {
		// Polymorphism 다형
				
        //1) 일반적인 방식의 객체 생성
		Father fa=new Father();
		fa.disp(); //아버지 주소
		
		Son son=new Son("손흥민","영국");
		son.disp(); //손흥민 영국
		
		Daughter daugh=new Daughter("김연아","캐나다");
		daugh.disp(); //김연아 캐나다
				
	}//main() end
}//class end

2)다형성을 이용한 객체를 생성

- 자식이 부모집에 들어가는 것 (자식클래스가 부모클래스에 대입가능)

- 그렇게 되면 부모클래스는 자식클래스의 모양으로 형태를 변경한다. (형변환) 모성애 

//main()
Father fa=new Son("개나리","코끼리"); //자식을 부모집에 넣으면 부모가 자식의 형태로 바뀜
fa.disp(); //개나리 코끼리
		
fa=new Daughter("진달래","원숭이");
fa.disp(); //진달래 원숭이
		

- 자식클래스에 추가된 멤버는 다형성의 대상이 아니다.

friend

- 부모역시 자식의 집에 들어갈 수 있다. 단, 제약조건 : 자식클래스의 모양으로 변환 후 대입해야한다.

//main()
Father father=new Father();
Son son=new Son();
Daughter daughter=new Daughter();
		
//에러는 아니지만 러닝과정에서 Exception 발생
father=son;         //자식이 부모에 대입
son=(Son) father; //부모가 자식에 대입
daughter=(Daughter) father;

java 이것이 자바다 신용권의 java프로그래밍 정복

 

Object

모든 자바클래스의 최고 조상

자바의 모든 클래스는 Object클래스의 후손이다                          ? 맞다

자바의 모든 클래스는 Object클래스에 대입가능하다(다형성이 된다) ? 맞다

1) 다형성 : 부모가 자식집에 들어가는 것 

Object obj=new Integer(5);
System.out.println(obj);  //5
		
obj=new String("soldesk");
System.out.println(obj);  //"soldesk"
		
obj=new Double(3.4);
System.out.println(obj); //3.4

//조상이 후손집에 들어가는 것 
Double dou=(Double) obj;
System.out.println(dou); //3.4

 

2) 메소드와 관련된 Object 클래스
-1 매개변수가 Object 클래스

package oop0604;

class Print {
//static : 클래스명으로 직접 접근 가능
//          클래스명.멤버변수
//          클래스명.멤버함수()
//method overloading : 매개변수의 자료형과 갯수로 구분
1. 각각의 자료형으로 view함수 만들기
	public static void view(Integer a){
		System.out.println(a.toString());
	}
	public static void view(Double a){
		System.out.println(a.toString());
	}
	public static void view(String a){
		System.out.println(a.toString());
	}
}//class end
2. 각각의 자료형을 object로 받아 하나의 view함수만들기
    public static void view(Object obj){
		System.out.println(obj.toString());
	}


//1) 매개변수가 Object 클래스
Print.view(new Integer(3)); //3
Print.view(new Double(5.6)); //5.6
Print.view(new String("Happy")); //"Happy"

 - autoboxing : 기본형 값이 전달되면 참조형으로 자동으로 형변환되어 출력된다.

Print.view(5.6); //5.6
Print.view(8);   //8
Print.view("Happy"); //"Happy"

-2 메소드의 리턴형이 Object클래스

package oop0604;

class Print {
	public static Integer disp1(){
		return new Integer(3);
	}
	
	public static Double disp2(){
		return 5.6; //autoboxing 
	}
	
	public static Object disp3(){
		return new Integer(9);
	}
	
    public static Object disp4(){
		return new Double(8.7);
	}
    
    public static Object disp5(){
		return "Happy";
	}
}//class end

public class Test04_Object {

	public static void main(String[] args) {
    
        Integer a=Print.disp1();
		System.out.println(a); //3
		
		Double b=Print.disp2();
		System.out.println(b); //5.6
		
		Object obj=Print.disp3();
		System.out.println(obj.toString()); //9
		
		Double c=(Double) Print.disp4(); //8.7 자식이 부모집에 들어가려면 형변환
		System.out.println(c);
		
		String d=(String) Print.disp5();
		System.out.println(d); //"Happy"
	}//main() end
}//class end
        

 -오버라이드 형태, 

//오버라이드
package oop0604;

class Screen {
	public String getData(){
		return "";
	}
}//class end

class TypeA extends Screen {
	@Override
	public String getData() {
		return "기생충";
	}
}//class end

class TypeB extends Screen {
	@Override
	public String getData() {
		return "어벤져스";
	}	
}//class end

public class Test05_Object {

	public static void main(String[] args) {
		// Object 클래스 : 자바의 최상위 클래스
		
		//1)다형성
		Screen scr=new TypeA();
		System.out.println(scr.getData()); //기생충

		scr=new TypeB();
		System.out.println(scr.getData()); //어벤져스
		
	}//main() end
}//class end

-Method Overloading 의 다형성 표기

package oop0604;

class Screen {
	public String getData(){
		return "";
	}
}//class end

class Picture {
	//1)Method Overloading
	public static void dispStar(TypeA ta){
		System.out.println(ta.getData());
	}
	public static void dispStar(TypeB tb){
		System.out.println(tb.getData());
	}
	//2)다형성
	public static void dispStar(Screen scr){
		System.out.println(scr.getData());
	}
	//3)다형성 
	public static void dispStar(Object obj){
		Screen scr=(Screen) obj;
		System.out.println(scr.getData());
	}
}//class end


public class Test05_Object {

	public static void main(String[] args) {
		// Object 클래스 : 자바의 최상위 클래스
		
		TypeA ta=new TypeA();
		TypeB tb=new TypeB();
		
		Picture.dispStar(ta); //기생충
		Picture.dispStar(tb); //어벤져스
		
	}//main() end
}//class end

Exception

: 예외처리

자바클래스 실행(run)시 발생하는 에러

에러는 아니지만 코딩 후 런할때 쓰레기값나오는거 

해결방안

- try~catch문

- throws문

- finally문

 

1) Exceptioin 처리하지 않은 경우

System.out.println(1); //1
System.out.println(2/0); //ArithmeticException발생 0으로 나누지마라
System.out.println("END"); //값이 출력되지않는다, 윗 SYSO에 EXCEPTION이 발생했기때문

2) Exception 처리한 경우

try { 
	//예외가 발생 예상이 되는 코드를 작성
	System.out.println(1);
	System.out.println(2/0);
	System.out.println(3);
} catch(ArithmeticException e ) {    //e는 변수명 ,메세지를 받을 변수명임,
	//예외가 발생되면 처리할 코드를 작성				
	System.out.println(e);
}//try end
System.out.println("END"); //프로그램이 정상적으로 종료되었다는 의미

출력결과
1
java.lang.ArithmeticException: / by zero
END

java.lang.ArithmeticException: / by zero 

-> 이 메세지가 나온건 에러가 아니라 변수 e로 받은 에러메세지이다. 이 메세지를 보고 원인을 보라는 표시

END

-> 클래스가 정상적으로 종료되었다는 의미

3) 배열에 Exception (ArrayIndexOutOfBoundsException)

try{
	System.out.println(1);
	int[] su=new int[3];
	su[3]=5;
	System.out.println(2);
}catch(ArrayIndexOutOfBoundsException e){
	System.out.println(e);
}//try end
System.out.println("END");

출력결과
1
java.lang.ArrayIndexOutOfBoundsException: 3
END

4) 형변환에 Exception (NumberFormatException)

try{
	System.out.println(1);
	int su=Integer.parseInt("soldesk");
	System.out.println(2);
}catch(NumberFormatException e){
	System.out.println(e);
}//try end
System.out.println("END");

출력결과
1
java.lang.NumberFormatException: For input string: "soldesk"
END

5) null Exception (NullPointerException)

try{
	System.out.println(1);
	Integer inte=null;
	int su=3/inte;
	System.out.println(2);
}catch(NullPointerException e){
	System.out.println(e);
}//try end
System.out.println("END");

출력결과
1
java.lang.NullPointerException
END

6) 다중 catch문

try{
	int a=Integer.parseInt("happy");
	int b=3/0;
	int[] su=new int[3];
	su[3]=5;
}catch(ArithmeticException e){
	System.out.println(e);
}catch(ArrayIndexOutOfBoundsException e){
	System.out.println(e);
}catch(NumberFormatException e){
	System.out.println(e);
}catch(NullPointerException e){
	System.out.println(e);
}//try end
System.out.println("END");

출력결과
java.lang.NumberFormatException: For input string: "happy"
END

7) 다형성을 이용한 예외처리

 - Exception 이라 표기한다면 , 모든 Exception 포괄가능

try{
	int a=Integer.parseInt("happy");
	int b=3/0;
	int[] su=new int[3];
	su[3]=5;
}catch(Exception e){ //Exception 클래스 -> 모든 exception의 조상 -> 다형성
	System.out.println(e);
}//try end
        
출력결과
java.lang.NumberFormatException: For input string: "happy"
END

8) Finally문

 - 예외가 발생하거나, 발생하지 않거나 무조건 실행한다.

 - Exception이 발생했는데 클래스를 제대로 마무리해주지 않으면, 다른 클래스에도 영향을 줄 수 있으니 

   finally문 적극 활용해서 마무리시켜준다.

 - exception이 발생하더라도, finally문을 거쳐 close를 출력하고, end를 출력한다.

try{
	System.out.println("OPEN");
	System.out.println(1);
	System.out.println(2/0);
	System.out.println(3);
}catch(Exception e){
	System.out.println(e);
}finally{
	System.out.println("CLOSE");
}//try end
System.out.println("END");

출력결과
OPEN
1
java.lang.ArithmeticException: / by zero
CLOSE
END

9) throw문

 - 메소드 호출시 에외처리를 한꺼번에 모아서 처리

package oop0604;

class Test {
	//1)try~catch를 이용한 예외처리
	
	public void view(){
		try{
			int a=3/0;
		}catch(Exception e){}
	}
	public void disp(){
		try{
			int a=Integer.parseInt("soldesk");
		}catch(Exception e){}
	}
	
	//2)throws를 이용한 예외처리 
	/*
	public void view() throws Exception{ //메소드를 호출할때에 exception받는다.
		int a=3/0;
	}
	public void disp() throws NumberFormatException{
		int a=Integer.parseInt("soldesk");
	}
}//class end
*/

public class Test07_Exception {

	public static void main(String[] args) {
		// throw문
		//메소드 호출시 에외처리를 한꺼번에 모아서 처리

		try{
			Test test=new Test();
			test.view();
			test.disp();
		}catch(Exception e){
			System.out.println(e);
		}//try end
		System.out.println("END");
		
		
		
		
		
		
		
		
	}//main() end
}//class end

 

GetSet 함수

getter 함수 - 가져오는거 , 리턴형있음

setter 함수 - 주는거,

package oop0604;

class Member {
	private String id;
	private String passwd;
	
	public void setId(String id){ //규칙 : set+Id 앞글자대문자 
		this.id=id;
	}
	public String getId(){
		return this.id;
	}
	
	public void setPasswd(String passwd){
		this.passwd=passwd;
	}
	public String getPasswd(){
		return this.passwd;
	}
}//class end

public class Test08_GetSet {

	public static void main(String[] args) {
		// getter, setter 함수
		
		Member mem=new Member();
		mem.setId("soldesk");
		mem.setPasswd("1234");
		System.out.println(mem.getId()); //soldesk
		System.out.println(mem.getPasswd()); //1234
		
	}//main() end
}//class end

-source ->getter&setter 만들기

sort는 getter&setter pair로 , 그래야 수정하기 편함

 


<연습문제>

문제 ) 성적프로그램 OX 표시하기

/*    
          ** 시험결과 **
====================================
번호 이름    1  2  3  4  5  점수 등수      
------------------------------------    
1    홍길동  ○ X  ○ ○ ○  80   2    
2    무궁화  ○ ○ ○ ○ ○ 100   1
3    라일락  X  X  X  X  ○  20   5
4    진달래  X  ○ X  ○ ○  60   3
5    봉선화  ○ ○ X  X  X   40   4
------------------------------------   

- 맞힌문제 ○ , 틀린문제 X표시
- 점수: ○당 20점씩
- 등수: 점수를 기준으로 높은사람이 1등
- 정렬: 등수를 기준으로 오름차순 정렬
*/

package oop0604;

class Sungjuk { //클래스는 한사람에 들어가는 정보로 설계해야함
	private int no;                                //번호  
	private String name;                       //이름
	private int[] answer = new int[5];     //답안제출
	private char[] ox = new char[5];       //OX표시
	public int score;                            //점수
	public int rank;                             //등수
	
	public Sungjuk(){}
	public Sungjuk(int no, String name, int a, int b, int c, int d, int e){
		this.no=no;
		this.name=name;
		this.answer[0]=a;
		this.answer[1]=b;
		this.answer[2]=c;
		this.answer[3]=d;
		this.answer[4]=e;
		this.rank=1;
	}
	
	public void compute(){
		//제출한 answer답안과 정답을 비교해서 OX를 구하고, 맞은 갯수에 따라 점수구하기 
		int[] dap={1,1,1,1,1}; //정답임
		for(int idx=0; idx<5; idx++){
			if(dap[idx]==answer[idx]){ //정답인지?
				ox[idx]='O'; //맞으면 o
				score=score+20; //점수 누적시켜주기
			}else{
				ox[idx]='X'; //틀리면 x	
			}
		}//for end
		
		/*me
		int size = dap.length;
		int ok=0; //맞은 갯수 카운트
			
		for(int a=0; a<size; a++){	
				if(answer[a]==dap[a]){ //답과 학생의 답이 같다면 o출력 아니면 x출력
					ok++;
					ox[a]='O';
					score=score+20;
				}else{
					ox[a]='X';
				}//if end			
		}//for end
		*/
	}//compute() end
	
	public void disp(){
		//출력하기
		System.out.print(no+" ");
		System.out.print(name+" ");
		System.out.print(ox[0]+" ");
		System.out.print(ox[1]+" ");
		System.out.print(ox[2]+" ");
		System.out.print(ox[3]+" ");
		System.out.print(ox[4]+" ");
		System.out.print(score+" ");
		System.out.print(rank+" ");
		System.out.println();
		
		/*me
		System.out.print(this.no);
		System.out.print(this.name);
		System.out.print(this.answer[0]);
		System.out.print(this.answer[1]);
		System.out.print(this.answer[2]);
		System.out.print(this.answer[3]);
		System.out.print(this.answer[4]);
		System.out.print(this.ox);
		System.out.print(this.score);
		System.out.print(this.rank);
		System.out.println();
		*/
	}//disp() end	
}//class end

public class Test09_OX {

	public static void main(String[] args) {
		// 성적프로그램 OX 프로그램
		// prtyimo.cafe24.com ->OOP ->글번호 25 참조
		
		Sungjuk[] student={
				new Sungjuk(1,"홍길동",1,2,1,1,1),
				new Sungjuk(2,"무궁화",1,1,1,1,1),
				new Sungjuk(3,"라일락",3,2,4,2,1),
				new Sungjuk(4,"진달래",2,1,4,1,1),
				new Sungjuk(5,"봉선화",1,1,4,3,2),				
		};
		
		int size=student.length;
		
		//1)점수계산하기
		for(int idx=0; idx<size; idx++){
			student[idx].compute(); 
		}//for end
		
		//2)등수구하기 
		//등수 알고리즘 이용 oop0522 test02_sungjuk
		for(int a=0; a<size; a++){
			for(int b=0; b<size; b++){
				if(student[a].score<student[b].score){ //.score변수가 안불러져왔다. 이유는 위에 private로 막아놨기때문에. 
					 student[a].rank=student[a].rank+1; //rank도 마찬가지. public으로 열어놔야한다
				}
			}//for
		}//for end
	
		
		//3)정렬하기(등수를 기준으로 오름차순 정렬)
		//oop0528 test03_sort 
		for(int a=0;a<size-1;a++){
			for(int b=0;b<size;b++){
				if(student[a].rank<student[b].rank){ //rank를 비교             
					Sungjuk tmp=student[a]; //밑 구문에도 rank변수로 비교를 해준다면, rank의 수만으로 비교가 되므로 
					                                    //맞지않다. student[] 전체를 움직여줘야하기때문에, student 변수를 적어준다.
					student[a]=student[b];
					student[b]=tmp;
				}//swap
			}//for
		}//for		
			
		//4)출력하기
		System.out.println("  **시험결과**  ");
		System.out.println("====================");
		System.out.println("번호  이름  1 2 3 4 5 점수 등수");
		System.out.println("------------------------------------");
		for(int idx=0; idx<size; idx++){
			student[idx].disp(); 			
		}//for end
		System.out.println("------------------------------------");
				
		/*
		for(int a=0; a<size; a++){
			student[a].disp();			
		}//for end
		*/
		
	}//main() end
}//class end

출력결과
  **시험결과**  
====================
번호  이름  1 2 3 4 5 점수 등수
------------------------------------
2 무궁화 O O O O O 100 1 
1 홍길동 O X O O O 80 2 
4 진달래 X O X O O 60 3 
3 라일락 X X X X O 20 5 
5 봉선화 O O X X X 40 4 
------------------------------------

'공부 > 자바 OOP' 카테고리의 다른 글

6월10일 - Java Collection Framework  (0) 2019.06.10
6월5일 - Abstract class + Interface  (0) 2019.06.05
6월3일 - 상속  (0) 2019.06.03
5월31일 - Wrapper 클래스  (0) 2019.05.31
5월30일 - this() / static / final  (0) 2019.05.30