본문 바로가기

취준생 일상

[내일배움카드/디지털컨버전스] 자바스프링기반 융합개발자 복습 2일차_클래스 만들기

< 복습 2일 차 >

 

클래스명 변수명 → 클래스의 객체를 참조하기 위한 참조변수를 선언

변수명 = new 클래스명(); → 클래스의 객체를 생성한 후, 객체의 주소를 참조변수에 저장

 

- Car 클래스 만들기

/*
	멤버변수 / 메소드

	클래스 → 객체 생성
*/
class Car {
	// 멤버변수
	String color;
	int speed;
	int gear;
	
	// 메소드
	void print(){
		System.out.println("(" + color + ", " + speed + ", " + gear +" )");

	}
}

//Car클래스 사용방법
public class CarTest {
	public static void main(String[] args) {
		
		// Car - 참조형, new Car - 객체를 만들겠다(객체생성) → 멤버변수&메소드 메모리에 올라간다./ new Car 객체를 myCar 대입
		Car myCar = new Car(); // 객체 생성
		myCar.color = "red";
		myCar.speed = 0;
		myCar.gear = 1;
		myCar.print(); // 메소드 호출. 메소드가 정의하고 있는거를 실행해라


		Car yourCar = new Car(); // 객체 생성
		yourCar.color = "blue";
		yourCar.speed = 60;
		yourCar.gear = 3;
		yourCar.print(); // 메소드 호출.
	}
}

 

결과

 

 

 

 

 

 

- Tv클래스 만들기

class Tv {
	//멤버변수
	String color;
	boolean power;
	int volume;

	//메서드
	void power() { 
		power = !power;
	}
	/*
		boolean -> true / false
		power의 값이 true면 false로, false면 true로 변경. (on/off)

	*/
	void volumeUp() {
		++volume;
	}
	void volumeDown() {
		--volume;
	}
}

class TvTest {
	public static void main(String[] args) {
		Tv t;
		t = new Tv();
		t.volume = 10;
		t.volumeUp();
		System.out.println("현재 소리는 " + t.volume + " 입니다.");

		
		t.power();
		System.out.println("현재 TV " + t.power + " 상태입니다.");

	}
}

결과