06
21
728x90

클래스의 구성 멤버

필드(Field) : 객체의 데이터가 저장되는곳

생성자(Constructor) : 객체 생성시 초기화 역할 담당

메소드(Method) : 객체의 동작에 해당하는 실행 블록


필드의 내용

객체의 고유 데이터

객체가 가져야할 부품 객체

객체의 현재 상태 데이터

 

필드 선언

타입 필드 [ = 초기값] ;
String company = "현대자동차" ;
String model = "그렌저";
int maxSpeed = 300;
---------------------------------------------------------
int productionYear;
int currentSpeed;
boolean engineStart;

기본값이 없는 필드는 객체가 생성될때 타입에 맞는 기본값으로 초기화가됨.

 

필드 타입별 기본 초기값

 

필드 사용

필드값을 읽고, 변경하는 작업을 말한다.

필드 사용 위치

객체 내부 : "필드 이름"으로 바로 접근
객체 외부 : "변수.필드이름"으로 접근

 

예제)

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);
	}
}

출력 결과

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);
	}
}

출력 결과

 

728x90
COMMENT