카테고리 없음

ch06 클래스

j_youngmin 2023. 2. 23. 00:31

ch06 클래스

 

 

 

package sec04.exam01_class_new;

public class Student { // 빈 객체가 될 클래스

}

 

 

package sec04.exam01_class_new;

public class StudentExample {
	public static void main(String[] args) { // 실행 메소드가 있는 실행 클래스
		Student s1 = new Student(); // 객체 생성해서, Studnet.java 클래스를 이용함
		System.out.println("s1 변수가 Student 객체를 참조합니다.");
		
		Student s2 = new Student();
		System.out.println("s2 변수가 또 다른 Student 객체를 참조합니다.");
	}
}

 

 

exam01_field_declaration

package sec06.exam01_field_declaration;

public class Car {
	//필드
	String company = "현대자동차";
	String model = "그랜저";
	String color = "검정";
	int maxSpeed = 350;
	int speed;
}
package sec06.exam01_field_declaration;

public class CarExample {
	public static void main(String[] args) {
		//객체 생성
		Car myCar = new Car(); // 객체 생성해서, 그 클래스에 있는 필드명 이용함
		
		//필드 값 읽기
		System.out.println("제작회사: " + myCar.company);
		System.out.println("모델명: " + myCar.model);
		System.out.println("색깔: " + myCar.color);
		System.out.println("최고속도: " + myCar.maxSpeed);
		System.out.println("현재속도: " + myCar.speed);
		
		//필드 값 변경
		myCar.speed = 60;
		System.out.println("수정된 속도: " + myCar.speed); // 앞 클래스 객체 클래스의 값 여기에서 변경 가능
	}
}

 

exam02_field_default_value

package sec06.exam02_field_default_value;

public class FieldInitValue {
	//필드
	byte byteField;
	short shortField;
	int intField;
	long longField;
	
	boolean booleanField;
	char charField;	
	
	float floatField;
	double doubleField;
	
	int[]  arrField;
	String referenceField;	
}

 

package sec06.exam02_field_default_value;

public class FieldInitValueExample {
	public static void main(String[] args) {	
		FieldInitValue fiv = new FieldInitValue();
		
		System.out.println("byteField: " + fiv.byteField);
		System.out.println("shortField: " + fiv.shortField);
		System.out.println("intField: " + fiv.intField);
		System.out.println("longField: " + fiv.longField);		
		System.out.println("booleanField: " + fiv.booleanField);
		System.out.println("charField: " + fiv.charField);		
		System.out.println("floatField: " + fiv.floatField);
		System.out.println("doubleField: " + fiv.doubleField);		
		System.out.println("arrField: " + fiv.arrField);
		System.out.println("referenceField: " + fiv.referenceField);
	}
}

 

실행 화면 필요

 

exam01_constructor_declaration

package sec07.exam01_constructor_declaration;

public class Car {
	//생성자
	Car(String color, int cc) { // 생성 메소드를 생성자라고 함
	}
}
package sec07.exam01_constructor_declaration;

public class CarExample {
	public static void main(String[] args) {
    
		Car myCar = new Car("검정", 3000); // 생성 메소드에 값 넣음
		//Car myCar = new Car();  (x)
	}
}

 

exam02_field_initialize

package sec07.exam02_field_initialize;

public class Korean {
	//필드
	String nation = "대한민국";
	String name;
	String ssn;

	//생성자
	/*public Korean(String n, String s) {
	  name = n;
	  ssn = s;
	}*/
	
	public Korean(String name, String ssn) {
	  this.name = name;
	  this.ssn = ssn;
	}
}
package sec07.exam02_field_initialize;

public class KoreanExample {
	public static void main(String[] args) {
    
		Korean k1 = new Korean("박자바", "011225-1234567");
		System.out.println("k1.name : " + k1.name);
		System.out.println("k1.ssn : " + k1.ssn);
		
		Korean k2 = new Korean("김자바", "930525-0654321");
		System.out.println("k2.name : " + k2.name);
		System.out.println("k2.ssn : " + k2.ssn);
	}
}

 

exam03_constructor_overloading

 

package sec07.exam03_constructor_overloading;

public class Car {
	//필드
	String company = "현대자동차";
	String model;
	String color;
	int maxSpeed;
	
	//생성자
	Car() {
	}
	
	Car(String model) {
		this.model = model;
	}
	
	Car(String model, String color) {
		this.model = model;
		this.color = color;
	}
	
	Car(String model, String color, int maxSpeed) {
		this.model = model;
		this.color = color;
		this.maxSpeed = maxSpeed;
	}
}
package sec07.exam03_constructor_overloading;

public class CarExample {
	public static void main(String[] args) {
    
		Car car1 = new Car();
		System.out.println("car1.company : " + car1.company);
		System.out.println();
		
		Car car2 = new Car("자가용");
		System.out.println("car2.company : " + car2.company);
		System.out.println("car2.model : " + car2.model);
		System.out.println();
		
		Car car3 = new Car("자가용", "빨강");
		System.out.println("car3.company : " + car3.company);
		System.out.println("car3.model : " + car3.model);
		System.out.println("car3.color : " + car3.color);
		System.out.println();
		
		Car car4 = new Car("택시", "검정", 200);
		System.out.println("car4.company : " + car4.company);
		System.out.println("car4.model : " + car4.model);
		System.out.println("car4.color : " + car4.color);
		System.out.println("car4.maxSpeed : " + car4.maxSpeed);
	}
}

 

 

exam04_other_constructor_call

package sec07.exam04_other_constructor_call;

public class Car {
	//필드
	String company = "현대자동차";
	String model;
	String color;
	int maxSpeed;
	
	//생성자
	Car() {
	}
	
	Car(String model) {
		this(model, null, 0);
	}
	
	Car(String model, String color) {
		this(model, color, 0);
	}
	
	Car(String model, String color, int maxSpeed) {
		this.model = model;
		this.color = color;
		this.maxSpeed = maxSpeed;
	}
}
package sec07.exam04_other_constructor_call;

public class CarExample {
	public static void main(String[] args) {
		Car car1 = new Car();
		System.out.println("car1.company : " + car1.company);
		System.out.println();
		
		Car car2 = new Car("자가용");
		System.out.println("car2.company : " + car2.company);
		System.out.println("car2.model : " + car2.model);
		System.out.println();
		
		Car car3 = new Car("자가용", "빨강");
		System.out.println("car3.company : " + car3.company);
		System.out.println("car3.model : " + car3.model);
		System.out.println("car3.color : " + car3.color);
		System.out.println();
		
		Car car4 = new Car("택시", "검정", 200);
		System.out.println("car4.company : " + car4.company);
		System.out.println("car4.model : " + car4.model);
		System.out.println("car4.color : " + car4.color);
		System.out.println("car4.maxSpeed : " + car4.maxSpeed);
	}
}

 

exam01_method_declaration

package sec08.exam01_method_declaration;

public class Calculator {
	//메소드
	void powerOn() { // void만 있는 메소드
		System.out.println("전원을 켭니다.");
	}
	
	int plus(int x, int y) {
		int result = x + y;
		return result;
	}
	
	double divide(int x, int y) {
		double result = (double)x / (double)y;
		return result;
	}
	
	void powerOff() {
		System.out.println("전원을 끕니다");
	}
}
package sec08.exam01_method_declaration;

public class CalculatorExample {
	public static void main(String[] args) {
		Calculator myCalc = new Calculator();
		myCalc.powerOn();
		
		int result1 = myCalc.plus(5, 6);
		System.out.println("result1: " + result1);
		
		byte x = 10;
		byte y = 4;
		double result2 = myCalc.divide(x, y);
		System.out.println("result2: " + result2);
		
		myCalc.powerOff();
	}
}

 

package sec08.exam01_method_declaration;

public class Computer {
	int sum1(int[] values) {
		int sum = 0;
		for(int i=0; i<values.length; i++) {
			sum += values[i];
		}
		return sum;
	}
	
	int sum2(int ... values) {
		int sum = 0;
		for(int i=0; i<values.length; i++) {
			sum += values[i];
		}
		return sum;
	}
}
package sec08.exam01_method_declaration;

public class ComputerExample {
	public static void main(String[] args) {
    
		Computer myCom = new Computer();
		
		int[] values1 = {1, 2, 3}; // 배열에 값 넣음
		int result1 = myCom.sum1(values1); // 
		System.out.println("result1: " + result1);
		
		int result2 = myCom.sum1(new int[] {1, 2, 3, 4, 5});
		System.out.println("result2: " + result2);		
		
		int result3 = myCom.sum2(1, 2, 3);
		System.out.println("result3: " + result3);
		
		int result4 = myCom.sum2(1, 2, 3, 4, 5);
		System.out.println("result4: " + result4);
	}
}

 

exam02_return

package sec08.exam02_return;

public class Car {
	//필드
	int gas;
	
	//생성자
	
	//메소드
	void setGas(int gas) {
		this.gas = gas;
	}
	
	boolean isLeftGas() {
		if(gas==0) {
			System.out.println("gas가 없습니다."); 
			return false;
		}
		System.out.println("gas가 있습니다."); 
		return true;
	}
	
	
	void run() {
		while(true) {
			if(gas > 0) {
				System.out.println("달립니다.(gas잔량:" + gas + ")");
				gas -= 1;
			} else {
				System.out.println("멈춥니다.(gas잔량:" + gas + ")");
				return;
			}
		}
	}
}

 

package sec08.exam02_return;

public class CarExample {
	public static void main(String[] args) {
		Car myCar = new Car();
		
		myCar.setGas(5);  //Car의 setGas() 메소드 호출
		
		boolean gasState = myCar.isLeftGas();  //Car의 isLeftGas() 메소드 호출
		if(gasState) { // if gasState == true라는 의미
			System.out.println("출발합니다.");
			myCar.run();  //Car의 run() 메소드 호출
		}
		
		if(myCar.isLeftGas()) {  //Car의 isLeftGas() 메소드 호출
			System.out.println("gas를 주입할 필요가 없습니다.");
		} else {
			System.out.println("gas를 주입하세요.");
		}
	}
}

 

exam03_method_call

package sec08.exam03_method_call;

public class Calculator {
	//필드
	//생성자
	//메소드
	int plus(int x, int y) {
		int result = x + y;
		return result;
	}
	
	double avg(int x, int y) {
		double sum = plus(x, y);
		double result = sum / 2;
		return result;
	}
	
	void execute() {
		double result = avg(7, 10);
		println("실행결과: " + result);
	}
	
	void println(String message) {
		System.out.println(message);
	}	
}

 

package sec08.exam03_method_call;

public class CalculatorExample {
	public static void main(String[] args) {
    
		Calculator myCalc = new Calculator();
		myCalc.execute();
	}
}

 

package sec08.exam03_method_call;

public class Car {
	//필드
	int speed;
	
	//생성자
	
	//메소드
	int getSpeed() {
		return speed;
	}
	
	void keyTurnOn() {
		System.out.println("키를 돌립니다.");
	}	
	
	void run() {
		for(int i=10; i<=50; i+=10) {
			speed = i;
			System.out.println("달립니다.(시속:" + speed + "km/h)");
		}
	}	
}

 

package sec08.exam03_method_call;

public class CarExample {
	public static void main(String[] args) {
    
		Car myCar = new Car();
		myCar.keyTurnOn();
		myCar.run();
		int speed = myCar.getSpeed();
		System.out.println("현재 속도: " + speed + "km/h");
	}
}

 

exam04_overloading

메소드 오버로딩(= 메소드 재정의)

부모 클래스의 멤버들을 자녀 클래스에서 상속할 때, 모든 메소드를 그대로 받아들이지 않고 수정해서 가져오는 것

 

package sec08.exam04_overloading;

public class Calculator {
	//정사각형의 넓이
	double areaRectangle(double width) {
		return width * width;
	}
	
	//직사각형의 넓이
	double areaRectangle(double width, double height) {
		return width * height;
	}	
}
package sec08.exam04_overloading;

public class CalculatorExample {
	public static void main(String[] args) {
		Calculator myCalcu = new Calculator();
		
		//정사각형의 넓이 구하기
		double result1 = myCalcu.areaRectangle(10);

		//직사각형의 넓이 구하기
		double result2 = myCalcu.areaRectangle(10, 20);
		
		//결과 출력
		System.out.println("정사각형 넓이=" + result1);
		System.out.println("직사각형 넓이=" + result2);
	}
}

 

exam01_instance_member

package sec09.exam01_instance_member;

public class Car {
	//필드
	String model;
	int speed;
	
	//생성자
	Car(String model) {
		this.model = model;
	}
	
	//메소드
	void setSpeed(int speed) {
		this.speed = speed;
	}
	
	void run() {
		for(int i=10; i<=50; i+=10) {
			this.setSpeed(i);
			System.out.println(this.model + "가 달립니다.(시속:" + this.speed + "km/h)");
		}
	}	
}
package sec09.exam01_instance_member;

public class CarExample {
	public static void main(String[] args) {
    
		Car myCar = new Car("포르쉐");
		Car yourCar = new Car("벤츠");
		
		myCar.run();
		yourCar.run();
	}
}

 

exam01_static_member

package sec10.exam01_static_member;

public class Calculator {
	static double pi = 3.14159;
	
	static int plus(int x, int y) {
		return x + y;
	}
	
	static int minus(int x, int y) {
		return x - y;
	}
}
package sec10.exam01_static_member;

public class CalculatorExample {
	public static void main(String[] args) {
    
		double result1 = 10 * 10 * Calculator.pi;
		int result2 = Calculator.plus(10, 5);
		int result3 = Calculator.minus(10, 5);
		
		System.out.println("result1 : " + result1);
		System.out.println("result2 : " + result2);
		System.out.println("result3 : " + result3);
	}
}

 

exam02_static_block

package sec10.exam02_static_block;

public class Television {
	static String company = "Samsung";
	static String model = "LCD";
	static String info;
	
	static {
		info = company + "-" + model;
	}
}
package sec10.exam02_static_block;

public class TelevisionExample {
	public static void main(String[] args) {
		System.out.println(Television.info);
	}
}

 

exam03_static_be_careful

package sec10.exam03_static_be_careful;

public class Car {
	int speed;
	
	void run() {
		System.out.println(speed + "으로 달립니다.");
	}
	
	public static void main(String[] args) {
		Car myCar = new Car(); 
		myCar.speed = 60;
		myCar.run();
	}
}

 

exam04_singleton

# 수업 코드 정리하고 가져올 것

package sec10.exam04_singleton;

public class Singleton {
	private static Singleton singleton = new Singleton();
	
	private Singleton() {}
	
	static Singleton getInstance() {
		return singleton;
	}
}
package sec10.exam04_singleton;

public class SingletonExample {
	public static void main(String[] args) {
		/*
		Singleton obj1 = new Singleton();  //컴파일 에러
		Singleton obj2 = new Singleton();  //컴파일 에러
		*/
		
		Singleton obj1 = Singleton.getInstance();
		Singleton obj2 = Singleton.getInstance();
		
		if(obj1 == obj2) {
			System.out.println("같은 Singleton 객체 입니다."); // 둘이 같으면 이곳으로
		} else {
			System.out.println("다른 Singleton 객체 입니다."); // 다르면 이곳으로
		}
	}
}

 

exam01_final

# final의 특성 다시 공부할 것

package sec11.exam01_final;

public class Person {
	final String nation = "Korea"; 
	final String ssn;
	String name;
	
	public Person(String ssn, String name) {
		this.ssn = ssn;
		this.name = name;
	}
}
package sec11.exam01_final;

public class PersonExample {
	public static void main(String[] args) {
    
		Person p1 = new Person("123456-1234567", "계백");
		
		System.out.println(p1.nation);
		System.out.println(p1.ssn);
		System.out.println(p1.name);
		
		//p1.nation = "usa";
		//p1.ssn = "654321-7654321";
		p1.name = "을지문덕";;
	}
}

 

exam02_static_final

package sec11.exam02_static_final;

public class Earth {
	static final double EARTH_RADIUS = 6400;
	static final double EARTH_SURFACE_AREA;
	
	static {
		EARTH_SURFACE_AREA = 4 * Math.PI * EARTH_RADIUS * EARTH_RADIUS;
	}	
}
package sec11.exam02_static_final;

public class EarthExample {
	public static void main(String[] args) {		
		System.out.println("지구의 반지름: " + Earth.EARTH_RADIUS + " km");
		System.out.println("지구의 표면적: " + Earth.EARTH_SURFACE_AREA + "  km^2");		
	}
}

 

exam01_package_compile

package sec12.exam01_package_compile;

public class Application {
	public static void main(String[] args) {
		System.out.println("애플리케이션을 실행합니다.");
	}
}

 

# 타이어 인터페이스를 콘크리트로 클래스들로 구상화하는 것은 선생님 강의 코드가 더 유용함

exam02_package_create

package sec12.exam02_package_create;

public class Car {

}

 

exam03_import

sec12