FIF's 코딩팩토리

자바 기초 NCS교육과정(14)-클래스 본문

카테고리 없음

자바 기초 NCS교육과정(14)-클래스

FIF 2019. 7. 11. 09:28
반응형

Java065_class.java

public class Java065_class {

	public static void main(String[] args) {
		Person ps; //객체선언
		ps=new Person(); //객체생성
		ps.name="홍길동";
		ps.age=30;
		ps.gen='M';
		System.out.printf("%s %d %c\n",ps.name,ps.age,ps.gen);
		ps.eat();
		ps.run();
		
		// 객체선언 및 생성
		Person pn=new Person();
		pn.name="이영희";
		pn.age=25;
		pn.gen='F';
		System.out.printf("%s %d %c\n", pn.name, pn.age, pn.gen);
		ps.eat();
		ps.run();
	}

}

 

Java066_class.java

  [도서관리]
  제목 대출여부
  칼의 노래  대출중
  어두운 상점의 거리 대출가능
 


  [객체 모델링]
  객체의 특징 : 제목, 대출여부
  객체의 기능 : 대출여부를 처리한다.
class Book {
	String title;
	boolean state;

	String process() {
		if (state) {
			return "대출가능";
		} else {
			return "대충 중";
		}
	}
}

public class Java066_class {

	public static void main(String[] args) {
		Book bk = new Book();
		bk.title = "칼의 노래";
		bk.state = false;

		Book bs = new Book();
		bs.title = "어두운 상점의 거리";
		bs.state = true;

		System.out.printf("%s, %s\n", bk.title, bk.process());
		System.out.printf("%s, %s\n", bs.title, bs.process());

	}// end main()

}//end class

 

Java067_class.java

[사각형 도형]
  가로 세로 넓이를 구한다 둘레를 구한다
  5 3 15 16
  7 4 28 22
  
  [객체모델링과정]
  객체의 특징: 가로, 세로
  객체의 기능 : 넓이를 구한다. 둘레를 구한다.
  
  [출력결과]
  [가로5, 세로3의 사각형]
  넓이:15
  둘레:16
  ====================
  [가로7,세로4의 사각형]
  넓이:28
  둘레:22
class Rect{
	int width; //가로
	int height;//세로
	
	//넓이를 구하는 메소드 정의
	int area() {
		return width*height;
	}
	
	//둘레를 구하는 메소드 정의
	int grith() {
		return(width+height)*2;
	}
	void prn() {
		System.out.printf("[가로%d, 세로%d]\n", width,height);
		System.out.printf("넓이:%d\n",area());
		System.out.printf("둘레:%d\n",grith());
	}
}

public class Java067_class {

	public static void main(String[] args) {
		Rect t1=new Rect();
		t1.width=5;
		t1.height=3;
		t1.prn();
		System.out.println("==============================");
		Rect t2=new Rect();
		t2.width =7;
		t2.height =4;
		t2.prn();

	}//end main()

}// end class

 

Java068_class.java

[출력결과]
메뉴명:떡볶이
가격:2000
갯수:3
메뉴금액:6000

메뉴명:김말이
가격:500
갯수:2
메뉴금액:1000

메뉴명:오뎅
가격:300
갯수:4
메뉴금액:1200
============
총금액:8200
public class Java068_class {

	public static void main(String[] args) {
		MenuShop m1 = new MenuShop();
		m1.menu="떡볶이";
		m1.price=2000;
		m1.cnt=3;
		m1.prn();
		
		MenuShop m2 = new MenuShop();
		m2.menu="김말이";
		m2.price=500;
		m2.cnt=2;
		m2.prn();
		
		MenuShop m3 = new MenuShop();
		m3.menu="오뎅";
		m3.price=300;
		m3.cnt=4;
		m3.prn();
		System.out.println("======================");
		int sum=m1.count()+m2.count()+m3.count();
		System.out.printf("총금액:%d",sum);
	}

}

 

Java069_variable.java

class MemberVar{
	//멤버변수는 기본값을 제공한다.(JVM)
	byte var_byte;//0
	short var_short;//0
	int var_int;//0
	long var_long;//0L
	float var_float;//0.0F
	double var_double; //0.0
	boolean var_boolean;//false
	char var_char; //\u0000
	int[] num; //null
}//end MemberVar

public class Java069_variable {

	public static void main(String[] args) {
		int num; //지역변수-기본값이 제공안됨
		//System.out.printf("num:%d\n",num);
		
		MemberVar mv =new MemberVar();
		System.out.printf("var_byte:%d\n",mv.var_byte);//0
		System.out.printf("var_short:%d\n",mv.var_short);//0
		System.out.printf("var_int:%d\n",mv.var_int);//0
		System.out.printf("var_long:%d\n",mv.var_long);//0
		System.out.printf("var_float:%.1f\n",mv.var_float);//0.0
		System.out.printf("var_double:%.1f\n",mv.var_double);//0.0
		System.out.printf("var_boolean:%b\n",mv.var_boolean);//false
		System.out.printf("var_char:%c\n",mv.var_char);
		System.out.printf("int[]:%s\n",mv.num);//null
	}

}

 

Java070_constructor.java

  생성자(constructor)
  1 멤버변수를 초기화하기 위한 목적으로 사용한다.(한번만 호출)
  2 클래스명과 같다.
  3 클래스는 한개 이상의 생성자는 갖는다.
  4 생성자는 리턴타입이 없다.
  5 클래스에 생성자가 정의되여 있지 않으면 JVM에서 기본생성자를 제공한다.
  6 기본생성자는 클래스의 접근제어자를 그대로 사용한다.
  
class HandPhone {
	// 멤버변수
	String name;
	String number;

	// 생성자
	HandPhone() {	}
	
	HandPhone(String ne, String nb){
		name=ne;
		number=nb;
	}

	// 메소드
	void prn() {
		System.out.printf("%s %s\n", name, number);
	}// end prn()
}

public class Java070_constructor {

	public static void main(String[] args) {
		/*
		 * 1. stack 영역에 4바이트 생성
		 * 		(객체변수 선언 : HandPhone ph)
		 * 2. heap영역에 HandPhone크기만큼 메모리 생성
		 * 		(new)
		 * 3. 멤버변수에 초기값을 할당
		 *    (생성자 호출: HandPhone())
		 * 4. heap의 주소를 stack에 저장
		 *    (=)
		 */
		HandPhone ph = new HandPhone();
		ph.name="홍길동";
		ph.number="010-2563-9029";
		ph.prn();
		
		HandPhone ne=new HandPhone("이영희","010-9725-8253");
		ne.prn();

	}

}

 

Java071_this.java

  this:메모에 생성된 자신을 의미한다.
  this.멤버변수;
  this.메소드();
  this();생성자
class Product {
	String code;
	String pname;
	int cnt;

	public Product() {

	}

	public Product(String code, String pname, int cnt) {//3
		// 멤버변수와 매개변수 이름이 같을 때 멤버변수에 this 키워드를 명시한다.
		this.code = code;//4
		this.pname = pname;//5
		this.cnt = cnt;//6
	}//7

	public void prn() {//9
		System.out.printf("%s %s %d\n", code, pname, cnt);//10
	}//11

	public void call() {
		// prn()
		this.prn();
	}
}// end Product

public class Java071_this {

	public static void main(String[] args) {//1
		Product pt = new Product("a001", "육류", 2);//2
		pt.prn();//8
	}//12

}

 

Java072_this.java

class Employees {
	String name;
	String dept;
	int salary;

	public Employees() {
		this("홍길동", "보류", 3000);
	}

	public Employees(String name, String dept, int salary) {
		this.name = name;
		this.dept = dept;
		this.salary = salary;
	}

	public void prn() {
		System.out.printf("%s %s %d\n", name, dept, salary);
	}

}

public class Java072_this {

	public static void main(String[] args) {
		Employees emp = new Employees("용팔이", "기획", 5000);
		emp.prn();
		Employees emp2 = new Employees();
		emp2.prn();

	}

}

 

Java073_class.java

class Song {
	String title;
	String artist;
	String album;
	String[] composer;
	int year;
	int track;

	public Song() {

	}

	public 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("[실행결과]");
		System.out.printf("노재 제목:%s\n", title);
		System.out.printf("가수:%s\n", artist);
		System.out.printf("앨범:%s\n", album);
		System.out.print("작곡가:");
		for (int i = 0; i < composer.length; i++) {
			char chk=i<composer.length-1 ? ',':'\n';
			System.out.printf("%s%c ",composer[i],chk);
			
			/*if (i < composer.length - 1) {System.out.printf("작곡가:%s, ", composer[i]);
			} else {System.out.printf("%s\n", composer[i]);
			}*/
		}
		System.out.printf("년도:%d\n", year);
		System.out.printf("트랙 번호:%d\n", track);

	}

}// end song

public class Java073_class {

	public static void main(String[] args) {
		Song s = new Song("Dansing Queen", "ABBA", "Arrival", new String[] { "Benny Anderson", "Bjorn Ulvaeus" }, 1977,
				2);
		s.show();

	}// end main()

}// end class

 

Java074_class.java

class Goods {
	String name;
	int price;
	int numberOfStock;
	int sold;

	public Goods() {

	}

	public Goods(String name, int price, int numberOfStock, int sold) {
		this.name = name;
		this.price = price;
		this.numberOfStock = numberOfStock;
		this.sold = sold;
	}

	public void prn() {
		System.out.printf("%-14s %8d %5d %5d\n", name, price, numberOfStock, sold);
	}

}// end Goods

public class Java074_class {

	public static void main(String[] args) {
		/*Goods g1 = new Goods("nikon", 400000, 30, 50);
		Goods g2 = new Goods("bbbb", 100000, 10, 40);
		Goods g3 = new Goods("ccc", 600000, 60, 90);
		g1.prn();
		g2.prn();
		g3.prn();*/
		
		Goods[] goodArray=new Goods[3];
		goodArray[0]=new Goods("nikon", 400000, 30, 50);
		goodArray[1]=new Goods("bbbb", 100000, 10, 40);
		goodArray[2]=new Goods("ccc", 600000, 60, 90);
		
		/*for(int i=0;i<goodArray.length ;i++) {
			goodArray[i].prn();
		}*/
		display(goodArray);
				
	}
	
	public static void display(Goods[] goodArray) {
		for(int i=0;i<goodArray.length ;i++) {
			goodArray[i].prn();
		}
	}//end display();

}

 

Java075_class.java

김병조/외과/39
이상만/내과/50
박상기/피부과/20
오상수/내과/25
윤달수/피부과/30



  [출력결과]
  박상기  피부과  20
  윤달수  피부과  30
class Doctor {
	String name; // 의사명
	String medical; // 진료과목
	int patient; // 대기환자수

	public Doctor(String name, String medical, int patient) {
		this.name = name;
		this.medical = medical;
		this.patient = patient;
	}

	public void prn() {
		System.out.printf("%s %s %d\n", name, medical, patient);
	}

}// end Doctor

public class Java075_class {

	public static void main(String[] args) {
		Doctor[] dt = new Doctor[5];
		// 여기를 구현하세요//////////
		dt[0] = new Doctor("김병조", "외과", 39);
		dt[1] = new Doctor("이상만", "내과", 50);
		dt[2] = new Doctor("박상기", "피부과", 20);
		dt[3] = new Doctor("오상수", "내과", 25);
		dt[4] = new Doctor("윤달수", "피부과", 30);
		//////////////////////
		search(dt, "내과");
	}// end main()

	public static void search(Doctor[] dt, String medical) {
		// 여기를 구현하세요/////////////
		for (int i = 0; i < dt.length; i++) {
			if (medical == dt[i].medical) {
				dt[i].prn();
			}
		}
	}
}// end class

 

Java076_class.java

  출력결과를 참조하여 process()메소드를 구현하시오.
  
  [출력결과]
  10 +  5 = 15
   3 *  2 = 6
class Calc {
	int first;
	int second;
	char ope;

	public Calc() {
	}

	public Calc(int first, int second, char ope) {
		this.first = first;
		this.second = second;
		this.ope = ope;
	}

	public int process() {
		// 여기를 구현하세요.////////////////
		/*if (ope == '+') {
			return first + second;
		} else if (ope == '-') {
			return first - second;
		} else if (ope == '*') {
			return first * second;
		} else{
			return first / second;
		}*/
		switch(ope) {
		case '+':
			return first + second;
		case '-':
			return first - second;
		case '*':
			return first * second;
		case '/':
			return first / second;
		}
		return 0;
		
		////////////////////////////////

	}// end process()

	public void prn() {
		System.out.printf("%2d %c %2d = %d\n", first, ope, second, process());
	}// end prn()
}// end Calc

public class Java076_class {

	public static void main(String[] args) {
		Calc[] nfo = null;
		// 여기를 구현하세요/////////////
		nfo=new Calc[2];
		nfo[0]=new Calc(10,5,'+');
		nfo[1]=new Calc(3,2,'*');
		/////////////////////
		display(nfo);
	}// end main( )

	public static void display(Calc[] nfo) {
		for (int i = 0; i < nfo.length; i++) {
			nfo[i].prn();
		}
	}// end display()
}// end class

 

Java077_class.java


  [데이터]
  a001  생명보험  자동차보험   30000
  a002  생명보험  운전자보험   20000
  b001  손해보험  화재보험      15000
  b002  손해보험  해상보험      25000
  
  [출력결과]
  손해보험 총납입액은 40000원 입니다.
class Insurance {
	String code; // 상품코드
	String name; // 상품명
	String type; // 상품종류
	int payment; // 납입보험료

	public Insurance() {

	}

	public Insurance(String code, String name, String type, int payment) {
		this.code = code;
		this.name = name;
		this.type = type;
		this.payment = payment;
	}

	public void prn() {
		System.out.printf("%s %s %s %d\n", code, name, type, payment);
	}
}// end Insurance

public class Java077_class {

	public static void main(String[] args) {
		String search = "손해보험";
		Insurance[] is = new Insurance[4];
		is[0] = new Insurance("a001", "생명보험", "자동차보험", 30000);
		is[1] = new Insurance("a002", "생명보험", "운전자보험", 20000);
		is[2] = new Insurance("b001", "손해보험", "화재보험", 15000);
		is[3] = new Insurance("b002", "손해보험", "해상보험", 25000);
		int sum = process(is, search);
		totalPrice(sum, search);

	}// end main( )

	public static int process(Insurance[] is, String name) {
		// 여기를 구현하세요////////////////
		int tot=0;
		for (int i = 0; i < is.length; i++) {
			if (name == is[i].name) {
				tot += is[i].payment;
			}
		}
		return tot;
	}// end process( )

	public static void totalPrice(int sum, String name) {
		System.out.printf("%s 총납입액은 %d원 입니다.\n", name, sum);
	}
}// end class

 

Java078_class.java

  [출력결과]
  기업은행 42523-52325 100000
  하나은행 52253-22623 153000
  신한은행 16239-95235 256000
  총납입액:509000
class CreditCard {
	String cardName;
	String cardNum;
	int pay;

	public CreditCard() {
	}

	public CreditCard(String cardName, String cardNum, int pay) {

		this.cardName = cardName;
		this.cardNum = cardNum;
		this.pay = pay;
	}

	public void prn() {
		System.out.printf("%s %s %d\n", cardName, cardNum, pay);
	}

}// end CreditCard

public class Java078_class {

	public static void main(String[] args) {
		/// [출력결과]를 참조하여 구현하시요/////////////////
		CreditCard[] cd = new CreditCard[3];
		cd[0] = new CreditCard("기업은행", "42523-52325", 100000);
		cd[1] = new CreditCard("하나은행", "52253-22623", 153000);
		cd[2] = new CreditCard("신한은행", "16239-95235", 256000);
		int sum = 0;
		for (int i = 0; i < cd.length; i++) {
			cd[i].prn();
			sum += cd[i].pay;
		}
		System.out.println("총납입액:" + sum);
	}// end main()

}// end class

 

Java079_overloading.java

  오버로딩(overloading)
  1 하나의 클래스에 같은 이름의 메서드를 여러개 정의 하는 것을 오버로딩이라한다.
  2 오버로딩의 조건
   1) 메서드의 이름이 같아야 한다.
   2) 매개변수의 갯수 또는 데이터 타입이 달라야 한다.
   3) 매개변수는 같고 리턴타입이 다른 경우는 오버로딩이 성립되지 않는다.
    (즉 리턴 타입은 오버로딩을 구현하는데 아무런 영향을 주지 않는다.)
class Calculator {
	void addValue(int x, int y) {
		System.out.println(x + y);
	}

	void addValue(int x, int y, int z) {
		System.out.println(x + y + z);
	}

	double addValue(double x, double y) {
		/* System.out.println(x+y); */
		return x + y;
	}
}

public class Java079_overloading {

	public static void main(String[] args) {
		Calculator cal = new Calculator();
		cal.addValue(4, 8);
		cal.addValue(2, 7, 5);
		System.out.println(cal.addValue(1.0, 2.0));
		
	}

}
반응형
Comments