6일차 - 생성자

|
package Constructor;

import java.util.Scanner;

/* 생성자 메소드
 * 의미 : 클래스에서 데이터를 주입시에 주로 사용합니다.
 * 생성자는 상속이 되지 않습니다.
 * 클래스명과 이름이 반드시 동일해야 합니다.
 * 반환 타입이 없습니다. return문을 사용하지 않습니다.
 * 접근제한자는 public이거나 생략가능합니다.
 * 그리고, 프로그래머가 생성자를 사용하지 않으면 JVM(Java Virtual Machine)이 자동으로 만들어 사용합니다.
 * 개발자가 작성한 생성자가 하나라도 존재하면, JVM은 기본 생성자를 만들지 않습니다.
 * 클래스에 전달되는 값을 클래스 변수에 초기화할 목적으로 사용합니다. 
 */

//문제] 두 개의 숫자를 입력받아서 생성자 메소드에 전달하고, 그 결과를 리턴받아 출력하는 프로그램을 작성합니다.
public class constSample1 {
	static int sum; // 클래스 변수는 자동으로 초기화됩니다. = 0; 300이 기억.
	static int i, j;
	
	public constSample1() {
		//default constructor : 아무것도 하지 않는 생성자.
	}
			
	
	public constSample1(int i, int j) { // 매개변수(오른쪽에 있는 i와 j)
		this.i = i; //100
		this.j = j; //200
		sum = i + j; // 100+200. 반환 타입이 없습니다. return문을 사용하지 않습니다.
	}

//	public static int AddSum() {
//		sum = i + j ;
//		return sum;
//	}
	
	public static void AddSum() {
		sum = i + j ;
	}

	public static void printDisplay() {
		System.out.println("4. 생성자를 이용한 초기화 연산값의 결과는  = " + sum);
	}
	
	public static void main(String[] args) {
		System.out.println("두 수를 입력해 주세요.");
		Scanner sc = new Scanner(System.in);
		int x = sc.nextInt();
		int y = sc.nextInt();
		constSample1 cs1 = new constSample1(x, y);
//		int result = AddSum(x,y);
//		System.out.println("1. Method result = " + result);
		System.out.println("2. 생성자를 이용한 합의 결과는  = " + constSample1.sum);
		
//		System.out.println("3. 메소드를 이용한 합의 결과는  = " + AddSum());
		
		AddSum(); // 연산 따로
		printDisplay(); // 출력 따로
		
		

	}



}


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

package Constructor;

import java.util.Scanner;

/*
 * 문제] 자동차 클래스가 있습니다.
 * 이 클래스에 색상과 가격을 입력하여 출력하세요. (임의적으로).
 * 단, 생성자 이용하여. 
 * 
 */

public class constSample2 {
	
	static String col;
	static int pri;

	public void constSample2(String col, int pri) {
		this.col = col;
		this.pri = pri;
	}
	
	public static String Display() {
		return "색상은 " + col + "이고, 가격은" + pri + "입니다.";
	}
	
	public static void main(String[] args) {
		System.out.println("원하는 자동차의 색상과 가격을 입력하세요.");
		Scanner sc = new Scanner(System.in);
		col = sc.next();
		pri = sc.nextInt();
		constSample2 col = new constSample2();
		constSample2 pri = new constSample2();
		System.out.println(constSample2.Display());

	}

}

'Bitcamp > BITCAMP - Java' 카테고리의 다른 글

7일차 - 생성자  (0) 2019.07.02
6일차 - 과제  (0) 2019.07.02
6일차 - 메소드 연습6  (0) 2019.07.01
6일차 - 메소드 연습5  (0) 2019.07.01
6일차 - 메소드 연습4  (0) 2019.07.01
And