본문 바로가기
코딩수업/AWS 클라우드환경 네이티브

8/8 자바(Java) 클래스 활용 연습, comparTo 함수, 상속

by 인생즐겜러 2022. 8. 8.
728x90
반응형

AWS 클라우드환경 네이티브 수업 57일차

 

 

 

진행

1. 자바 클래스 활용 연습

2. 상속

 

 

 

 

 

요약

1. comparTo 함수

2. 상속

 

 

 

 


 

 

 

 

 

자바 클래스 활용 연습1.

과일 구매자와 판매자 클래스를 각각 만들고

각 구매자가 판매자에게 과일을 산 후에

각자의 과일의 남은 갯수와 돈을 출력해보자.

 

 

package Question;


// 판매자
class seller {
			int numOfApple;
			int profit	;
		 	int ApplePrice	;
	
	
	// 초기 데이터
	public void initSeller(int money, int appleNum, int price) {
		profit = money;
		numOfApple = appleNum;
		ApplePrice = price;
	}
	
	public int saleApple(int money) {
		int num = money / ApplePrice;
		profit += money;
		numOfApple -= num;
		return num;
	}
	
	public void showSale() {
		System.out.println("남은 사과의 갯수 : " + numOfApple);
		System.out.println("금일 수익 : " + profit);	
	}
	
}



// 구매자
class buyer{
	int Money ;
	int numOfApple ;
	

	
	public void BuyApple(seller seller,int money) {
		numOfApple += seller.saleApple(money) ;
		Money -= money;	
	}
	
	
	public void showBuy() {
		System.out.println("남은 돈 : " + Money);
		System.out.println("구매한 사과의 갯수 : " + numOfApple);			
	}
	
}



// 메인
public class fruit {

	public static void main(String[] args) {
		
		// 사과 판매자들 초기값
		seller seller1 = new seller();
		seller1.initSeller(0, 100, 1000);
				
		seller seller2 = new seller();
		seller2.initSeller(10000, 50, 1300);
		
		seller seller3 = new seller();
		seller3.initSeller(5000, 70, 1500);
		
		
		
		// 구매자					
		buyer buyer1 = new buyer();
		buyer buyer2 = new buyer();
		
		buyer1.BuyApple(seller2, 3900);
		buyer1.BuyApple(seller3, 4500);

		
		System.out.println("과일 판매자 1의 상황");
		seller1.showSale();
		System.out.println("과일 판매자 2의 상황");
		seller2.showSale();
		System.out.println("과일 판매자 3의 상황");
		seller3.showSale();
		
		System.out.println("과일 구매자 1의 상황");
		buyer1.showBuy();
		System.out.println("과일 구매자 2의 상황");
		buyer2.showBuy();
	}

}



결과
과일 판매자 1의 상황
남은 사과의 갯수 : 100
금일 수익 : 0
과일 판매자 2의 상황
남은 사과의 갯수 : 47
금일 수익 : 13900
과일 판매자 3의 상황
남은 사과의 갯수 : 67
금일 수익 : 9500
과일 구매자 1의 상황
남은 돈 : -8400
구매한 사과의 갯수 : 6
과일 구매자 2의 상황
남은 돈 : 0
구매한 사과의 갯수 : 0

 

 

 

 

 


 

 

 

 

 

자바 클래스 활용 연습2.

연습 1을 생성자를 이용하여 재구성해보자.

 

 

package Question;

// 판매자
class seller {
			int numOfApple;
			int profit	;
	final 	int ApplePrice	;
	// final의 선언과 동시에 값을 지정해야하나, 생성자로 초기화 지정을 할 수 있다.
	
	
	// 초기 데이터를 생성자로 만든다.
	public seller(int money, int appleNum, int price) {
		profit = money;
		numOfApple = appleNum;
		ApplePrice = price;
	}
	
	public int saleApple(int money) {
		int num = money / ApplePrice;
		profit += money;
		numOfApple -= num;
		return num;
	}
	
	public void showSale() {
		System.out.println("남은 사과의 갯수 : " + numOfApple);
		System.out.println("금일 수익 : " + profit);	
	}
	
}



// 구매자
class buyer{
	int Money ;
	int numOfApple ;
	
	
	// 초기화
	public buyer(int money) {
		Money = money;
		numOfApple = 0;
	}
	
	public void BuyApple(seller seller,int money) {
		numOfApple += seller.saleApple(money) ;
		Money -= money;	
	}
	
	public void showBuy() {
		System.out.println("남은 돈 : " + Money);
		System.out.println("구매한 사과의 갯수 : " + numOfApple);			
	}
	
}



// 메인
public class fruit {

	public static void main(String[] args) {
		
		// 사과 판매자들 초기값
		seller seller1 = new seller(0, 100, 1000);
				
		seller seller2 = new seller(10000, 50, 1300);
		
		seller seller3 = new seller(5000, 70, 1500);
		
		
		
		// 구매자					
		buyer buyer1 = new buyer(0);
		buyer buyer2 = new buyer(0);
		
		buyer1.BuyApple(seller2, 3900);
		buyer1.BuyApple(seller3, 4500);

		
		System.out.println("과일 판매자 1의 상황");
		seller1.showSale();
		System.out.println("과일 판매자 2의 상황");
		seller2.showSale();
		System.out.println("과일 판매자 3의 상황");
		seller3.showSale();
		
		System.out.println("과일 구매자 1의 상황");
		buyer1.showBuy();
		System.out.println("과일 구매자 2의 상황");
		buyer2.showBuy();
	}
}

 

 

 

 

 


 

 

 

 

 

배열 및 클래스를 이용하여

수정 및 등록이 되는 전화번호부 만들어보기.

 

package Phone;

import java.util.Scanner;

// 초기 변수들 선언
class PhoneInfo{
	String name;
	String phoneNumber;
	String birth;
	
	public PhoneInfo(String name,String phoneNumber, String birth ){
		this.name			= name;
		this.phoneNumber	= phoneNumber;
		this.birth			= birth;
		
	}
	
	public PhoneInfo(String name,String phoneNumber) {
		this.name			= name;
		this.phoneNumber	= phoneNumber;		
		this.birth			= null;
	}	
	
	public void showPhoneInfo(){
		
		System.out.println("===================================");
		System.out.println("이    름 : " + name);
		System.out.println("전화번호 : " + phoneNumber);
		if(birth != null) {
			System.out.println("생년월일 : " + birth);			
		}
	}
}



//프로그램 시작 시 메뉴
class MenuViewer{
	public static Scanner typing = new Scanner(System.in);

	public static void showMenu() {
		System.out.println("원하는 작업을 고르세요");
		System.out.println("0. 프로그램 종료");
		System.out.println("1. 전화번호 입력");
		System.out.println("2. 이름으로 전화번호 검색 ");
		System.out.println("3. 이름으로 전화번호 삭제 ");
		System.out.print("무엇을 원하시죠? : ");		
	}	
}



//각 선택에 따른 기능
class bookManage{
	
	// 메모리 담을 참조변수 100개 생성
	final int MAX_CNT	= 100;
	PhoneInfo[] infoStorage = new PhoneInfo[MAX_CNT];
	
	// 어디 방까지 저장되어 있는지 확인할 변수
	int curCnt = 0;
		
	// 등록
	public void choice1() {
		System.out.print("이름 : ");		
		String name = MenuViewer.typing.nextLine();	
		System.out.print("전화번호 : ");		
		String phone = MenuViewer.typing.nextLine();		
		System.out.print("생년월일 : ");		
		String birth = MenuViewer.typing.nextLine();		
			
		infoStorage[curCnt++] = new PhoneInfo(name, phone, birth);
		System.out.println("전화번호 등록이 완료되었습니다.");
	}
		
	// 삭제
	public void choice3(){
		
		System.out.print("데이터 삭제를 시작합니다.");

		System.out.print("이름 : ");
		String name = MenuViewer.typing.nextLine();
		
		int dataIdx = search(name);
		if(dataIdx < 0){
			System.out.println("입력하신 이름이 없습니다.");
		} else {
			for( int idx = dataIdx; idx < curCnt-1 ; idx++ ) {
				infoStorage[idx] = infoStorage[idx+1];				
			}
			curCnt--;
			
			System.out.println("삭제가 완료되었습니다.");
		}	
	}
	
	// 조회
	public void choice2(){
		
		System.out.print("이름 : ");
		String name = MenuViewer.typing.nextLine();
		
		int dataIdx = search(name);
		if(dataIdx < 0){
			System.out.println("입력하신 이름이 없습니다.");
		} else {
			infoStorage[dataIdx].showPhoneInfo();
			System.out.println("데이터 검색이 완료되었습니다.");
		}	
	}
	
	
	// 검색 데이터가 배열 어디에 있는지 찾는 메소드
	private int search(String name) {
		for(int idx = 0 ; idx < curCnt ; idx++) {
			PhoneInfo curInfo = infoStorage[idx];
			
			// compareTo는 비교를 하는 함수
			if(name.compareTo(curInfo.name)==0) {
				return idx;
			}
		}
		
		return -1;
	}
}





public class phone1 {
	
	public static void main(String[] args) {
		
		bookManage manage = new bookManage();
		int choice = 0 ;
		
		while(true) {	
			MenuViewer.showMenu();	// 메뉴 출력
			
			choice = MenuViewer.typing.nextInt();	// 메뉴 선택 받기
			MenuViewer.typing.nextLine();
			
			switch(choice) {
				case 1: manage.choice1();
					break;					
				case 2: manage.choice2();
					break;	
				case 3: manage.choice3();
					break;	
				case 0 : 
					return;			
			}
		}		
	}
}



결과
원하는 작업을 고르세요
0. 프로그램 종료
1. 전화번호 입력
2. 이름으로 전화번호 검색 
3. 이름으로 전화번호 삭제 
무엇을 원하시죠? : 1
이름 : 홍길동
전화번호 : 012457802
생년월일 : 601012
전화번호 등록이 완료되었습니다.
원하는 작업을 고르세요
0. 프로그램 종료
1. 전화번호 입력
2. 이름으로 전화번호 검색 
3. 이름으로 전화번호 삭제 
무엇을 원하시죠? : 1
이름 : 이상해씨
전화번호 : 7447474474
생년월일 : 970312
전화번호 등록이 완료되었습니다.
원하는 작업을 고르세요
0. 프로그램 종료
1. 전화번호 입력
2. 이름으로 전화번호 검색 
3. 이름으로 전화번호 삭제 
무엇을 원하시죠? : 2
이름 : 이상해씨
===================================
이    름 : 이상해씨
전화번호 : 7447474474
생년월일 : 970312
데이터 검색이 완료되었습니다.
원하는 작업을 고르세요
0. 프로그램 종료
1. 전화번호 입력
2. 이름으로 전화번호 검색 
3. 이름으로 전화번호 삭제 
무엇을 원하시죠? :

 

 

 

 

 


 

 

 

 

 

comparTo 함수

 

compareTo() 함수는 두 개의 값을 비교하여 int 값으로 반환해주는 함수

구조는 아래와 같다.

 

기준값.compareTo(비교값)

 

 

 

 

 

숫자 비교 시

 

기준 결과값
기준값 == 비교값 0
기준값 < 비교값 -1
기준값 > 비교값 1

 

 

 

 

 

문자열 비교 시

 

기준 결과값
첫째자리부터 다를 시
(abcd와 c)
기준값 첫째자리 - 비교값 첫째자리 의 아스키코스 차이값
( a - c 의 아스키코드 차이값 )
2번째자리 이후부터 다를 시 
(abcd와 a)
값이 다른 길이만큼 출력
(3)

 

 

 

참고로 해당 함수는 대소문자를 다른 문자로 취급한다.

따라서 아스키코드도 대소문자에 적용되는 아스키코드로 비교를 하게 된다.

대소문자를 똑같이 취급하는 compareToIgnorecase() 함수도 있다.

 

 

 

 

 


 

 

 

 

 

상속

 

자식 클래스가 부모 클래스의 기능을 그대로 물려받을 수 있는 기능이다.

(생성자 제외)

 

구조는 아래와 같다.

 

class 자식클래스이름 extends 부모클래스이름{

}

 

 

 

 

 

아래의 예를 보면서 이해해보자.

Tv 클래스(부모클래스)의 모든 변수들을

UpgradeTv 클래스(자식클래스) 가  extends 구문을 이용해서

상속 받아 출력되는 것을 볼 수 있다.

 

package object;

class Tv{
	
	boolean power;
	int channel;
	boolean caption;

	void power()	{	power = !power;	}
	void channelUp()	{	++channel;		}
	void channelDown()	{	--channel;		}	
}

class UpgradeTv extends Tv{
	
	void displayOption(String text)	{
		if(caption) {
			System.out.println(text);
		}
	}
	
	
}

public class Lecture {

	public static void main(String[] args) {

		UpgradeTv kingTV = new UpgradeTv();
		kingTV.channel = 10;
		kingTV.channelUp();
		
		System.out.println("현재 채널 : " + kingTV.channel);
		
		
		kingTV.caption = true;
		kingTV.displayOption("자막 나올거다 이제");
	}	
}



결과
현재 채널 : 11
자막 나올거다 이제

 

 

 

부모 - 자식1, 자식1 - 자식2

이런 식으로 상속이 되어있을 때

자식2는 부모, 자식1의 모든 변수와 메소드를 받을 수 있다. 

이는 무한히도 가능하며 그만큼 메모리를 먹을 뿐이다.

 

단, 자바에서는 여러개 상속이 한 번에 되지 않는다.

아래의 예를 보자.

 

package object;

class TV{
	boolean power;
	int channel;
	void power() {
		power = !power;
	}
	void chaanelUp() {
		++channel;
	}
	void chaanelDown() {
		--channel;
	}
}

class VCR{
	boolean power;
	int count = 0;
	void power() {
		power = !power;
	}
	void play() {}
	void stop() {}
	void ff() {}
	void rew() {}
}


public class Lecture extends TV, VCR {
	// 상속을 이렇게 2개를 받을 수 없다.
	
	public static void main(String[] args) {
	}
}

 

위처럼 상속은 불가능 하다.

메인 클래스가 다 상속을 받게 하려면

아래처럼 

1. 상속 1개를 받고 다른 1개는 객체로 포함시키거나

2. 순차적으로 상속을 받게 한다.

 

1.

public class Lecture extends TV {
	// 상속
	
	public static void main(String[] args) {
		VCR vcr = new VCR();
		// 객체 생성으로 포함		
	}
}

 

2.

package object;

class TV{
	...
}

class VCR extends TV{
	//상속
    
	...
}


public class Lecture extends VCR {
	// 연속 상속
	
	public static void main(String[] args) {		
	}
}

 

728x90
반응형

댓글