본문 바로가기
  • Coding & Book
학습단/JAVA 학습단

6. 혼공자 6일차(클래스)

by 루이3 2023. 7. 10.

6일차

1. 객체

  • 객체는 자신의 속성을 가지고 있고 식별이 가능한것을 말합니다.(ex 자전거, 비행기)
  • 객체는 속성동작으로 구성되어 있고 각각 필드메소드라고 부릅니다.
  • 대부분의 객체는 다른 객체와 관계를 맺고 있습니다.
  • 관계의 종류로 집합관계, 사용관계, 상속 관계가 있습니다.

 

 

2. 클래스

클래스는 객체의 설계도와 비슷하다고 볼수 있습니다.

클래스로부터 만들어진 객체를 해당 클래스의 인스턴스라고 합니다.

클래스는 라이브러리용과 실행용 으로 두가지 용도가 있습니다.

라이브러리 클래스는 다른 클래스를 이용할 목적으로 사용합니다.

클래스는 필드, 생성자, 메소드로 구성되어 있습니다

 

---조건---

하나 이상의 문자로 이루어져있을 것
첫글자에 숫자를 쓰지 말 것
특수문자를 사용하지 말것($ 과 _ 는 제외 입니다.)
자바 키워드는 사용하지 말것

클래스 선언)

package sec06.exam01;

public class Student {

}

클래스로부터 객체 생성)

package sec06.exam01;

public class StudentExample {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Student s1 =new Student();
		System.out.println("s1이 객체를 참조합니다.");
	}

}

 

 

3.필드

  • 필드는 클래스 내부에 선언된 변수를 말합니다.
  • 필드 선언은 클래스 중괄호 {} 내에 어디든 사용해도 됩니다.

 

클래스 필드 선언)

package sec06.exam01;

public class Car {
	//필드
	String company ="현대";
	String model ="그랜저";
	String color ="검정";
}

 

package sec06.exam01;

public class CarExample {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Car myCar = new Car();
		System.out.println(myCar.company);
		System.out.println(myCar.model);
		System.out.println(myCar.color);
	}

}

 

4.생성자

  • new 연산자로 클래스로부터 객체를 생성할때 호출되어 객체의 초기화를 담당합니다.
  • 클래스를 객체생성할때 호출되는 메서드 입니다.
  • 객체 초기화는 필드를 초기화 하거나 메소드를 호출해서 객체를 사용할 준비를 하는것을 말합니다.
  • 모든 클래스는 생성자반드시 존재합니다.
  • 생성자에서 초기값을 줄수 있습니다.
package sec06.exam01;

public class Korean {
	String nation = "대한민국";
	String name;
	String ssn;
	
	//생성자
	public Korean(String n, String s) {
		name = n;
		ssn = s;
	}
}
package sec06.exam01;

public class KoreaExample {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Korean k1 =new Korean("전우치", "123456-7890");
		System.out.println(k1.name);
		System.out.println(k1.ssn);
	}

}

 

 

5. 생성자 오버로딩

  • 매개 변수를 달리하는 생성자를 여러개 선언하는것을 말합니다
  • 다양한 방법으로 객체를 생성할수 있도록 생성자 오버로딩을 제공합니다.

 

6. this()

  • 다른 생성자를 호출 할때 this()를 사용 합니다.
  • this()를 사용하여 생성자간의 호출관계를 설정할수 있습니다.
package sec06.exam01;

public class Car {
	String company ="현대";
	String model;
	String color;
	int maxSpeed;
	
	Car() {
	}
	
	Car(String model) {
		this(model, "은색", 250);
	}
	
	Car(String model, String color) {
		this(model, "은색", 250);
	}
	
	Car(String model,String color, int maxSpeed) {
		this.model = model;
		this.color =color;
		this.maxSpeed =maxSpeed;
	}
}
package sec06.exam01;

public class CarExample {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Car myCar3 = new Car("택시", "검정");
		System.out.println(myCar3.company);
		System.out.println(myCar3.model);
		System.out.println(myCar3.color);
	}

}

'학습단 > JAVA 학습단' 카테고리의 다른 글

8. 혼공자 8일차(상속)  (0) 2023.07.13
7. 혼공자 7일차(메소드)  (0) 2023.07.11
1주차 완료  (0) 2023.07.07
5. 혼공자 5일차(참조 타입)  (0) 2023.07.07
4. 혼공자 4일차(조건문 + 반복문)  (0) 2023.07.06