자바 학습 & 복습 9일차 - 객체 생성 & 사용

728x90

한 파일에 여러 class 작성하기 

소스파일의 이름은 public 클래스의 이름과 반드시 일치해야함

public 클래스가 없는경우 이름을 변경하여 여러 class를 작성해도 문제없음

다만 되도록 하나의 소스파일에서 하나의 class만 생성하는 것이 바람직

//public class가 있는경우
public class ATestVer {}
class java2{}
class hello2{}

// public class가 없는경우
class java{}
class hello{}

객체 생성 & 사용

class의 객체를 생성하여 각각의 설정된 기능을 호출하고 속성에 값을 지정하여 사용한다

순서: class 생성 > 객체 생성 (TV t = new TV() ) > 객체 속성값 지정 > 객체 기능 메서드 호출 후 사용

public class ClassPractice {
	public static void main(String[] args) {
//		객체를 지정할 때는 =
//		해당 클래스의 이름 변수 = new 해당 클래스()
//		TV라는 객체를 t라는 리모콘에 연결해서 new 새로운 TV를 컨트롤 할 수 있게 변경
		TV t = new TV();
		t.channel = 7;
//		TV인스턴스 멤버변수 channel 의 값을 7로 배정
		t.color = "검은색";
//		TV인스턴스 멤버변수 color을 검은색으로 배정
		
		t.channeldown();
		t.channelup();
//		channeldown()과 channelup()이라는 메소드를 호출
		System.out.println("현재채널은 " + t.channel + "번 입니다");
		System.out.println("현재 TV의 색깔은 " + t.color + "입니다");
		System.out.println("채널을 한개 내립니다: " + (t.channel + t.channeldown));
		System.out.println("채널을 한개 올립니다: " + (t.channel + t.channelup));
	}
}
//1. TV class를 먼저 생성함
class TV {
//	TV의 속성을 각각의 타입에 맞춰서 설정 = 멤벼변수
	String color;
	int channel;
	int channelup;
	int channeldown;
	boolean power;
	
//	TV의 호출메서드를 각각의 기능에 맞춰 조건문 설정
//	각각의 기능은 return값이 없고 동작만 하는 기능이므로 void값을 주어서 돌아오는 값이 있으면 오류를 반환한다.
	void power() {
		power =! power;
	}
	void channelup() {
		++channelup;
	}
	void channeldown() {
		--channeldown;
	}
}
728x90