this
- 자신의 클래스 내부에 있는 필드, 생성자에 접근하기 위한 자가 자신의 instance
this() 생성자
package chapter07;
public class Car2 {
// 필드
String color;
String company;
String type;
Car2() {
this("white", "기아", "경차");
}
Car2(String color, String company, String type) {
this.color = color;
this.company = company;
this.type = type;
}
Car2(String com, String t) {
this("white", com, t);
}
Car2(String t) {
this("white", "기아", t);
}
public String toString() {
return color + "-" + company + "-" + type;
}
}
this : 필드 접근
- getter(필드값 가저오기), setter(필드값 대입하기) 작성시 활용
- 은닉화, VO(Value Object), DTO(Data Transfer Object)와 연결됨
- private 으로 외부 접근을 제어, 메서드를 통해 필드에 접근
클래스 생성
package chapter07;
public class Student3 {
// 필드 : private 외부클래스에 접근 불가
private String name; // 학생명
private int grade; // 학년
private String department; // 학과
// getter, setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
}
클래스 사용
package chapter07;
public class StudentMain3 {
public static void main(String[] args) {
Student3 stu1 = new Student3(); // 기본생성자
//stu1.name = "홍길동" // 접근 불가
// set
stu1.setName("홍길동");
stu1.setGrade(4);
stu1.setDepartment("자바");
// get
String name = stu1.getName();
int grade = stu1.getGrade();
String department = stu1.getDepartment();
System.out.println("name="+name);
System.out.println("grade="+grade);
System.out.println("department="+department);
}
}
초기화 블록
- 클래스 필드의 초기화만을 담당하는 중괄호({})로 둘러싸인 블록
- 초기화 블록은 생성자보다 먼저 호출
- static 초기화 블록 : 클래스 instance 생성시 한 번 실행됨
- 인스턴스 초기화 블록 : 클래스 instance 생성시 매 번 실행됨
package chapter07;
class InitBlockEx{
int x;
static int A ;
static {
test();
A++;
System.out.println("static block A : " + A);
}
{
instanceMethod();
x++;
System.out.println("instance block x : " + x);
}
static void test() {
A++;
System.out.println("static method A : " + A);
}
public InitBlockEx() {
instanceMethod();
x++;
System.out.println("contsructor A, x : " + A +"," + x);
}
private void instanceMethod() {
x++;
System.out.println("instance method x : " + x);
}
}
package chapter07;
public class InitBlockTest {
public static void main(String[] args) {
InitBlockEx a = new InitBlockEx();
}
}
패키지
- 자바에서 많은 클래스들을 분류하기 위한 방법
- C#이나 다른 언어에서는 네임스페이스 라고 불려짐
- package 란 비슷한 기능을 하는 클래스를 묶어 놓은 단위
- 물리적으로는 클래스를 모아 놓은 디렉토리(폴더) 임
- 패키지명은 중복을 피하기 위해 일반적으로 유일한 이름인 도메인명을 꺼꾸로 사용해서 만듬
- 클래스이름은 실제적으로 상위패키지.하위패키지.클래스명
- String 클래스 : java.lang.String
- 이클립스 JRE System Library 확인, 프로젝트 scr 확인
- 클래스 실행 : 패키지 최상위에서 java 상위패키지.하위패키지.클래스명 실행
다른 패키지에 있는 클래스 사용
- 일반적으로 패키지 import 해서 사용
- import 패키지.* : 패키지 내 모든 클래스 사용, 하위 패키지는 적용 안됨
package greeting.korea;
public class Hello {
public Hello() {
System.out.println("greeting.korea.Hello");
}
}
- src/greeting/korea/Hello.java
- src/greeting/korea/Hello.class
package greeting.usa;
public class Hello {
public Hello() {
System.out.println("greeting.usa.Hello");
}
}
- src/greeting/usa/Hello.java
- src/greeting/usa/Hello.class
접근 제한자
- 멤버 또는 클래스에 사용
- 해당하는 멤버 또는 클래스를 외부에서 접근하지 못하도록 제한하는 역할
- 사용하는 곳 : 클래스, 멤버변수, 메서드, 생성자
- private : 같은 클래스 내에서만 접근 가능
- default: 같은 패키지 내에서만 접근 가능(접근 클래스를 붙이지 않은 경우)
- protected: 같은 패키지 내에서, 그리고 다른 패키지의 자손클래스에서 접근 가능
- public: 접근 제한 없음
package chapter07;
public class AccessEx {
private int a = 1;
protected int b = 2;
int c = 3;
public int d = 4;
}
각 접근 제한자 사용 - 같은 패키지
package chapter07;
public class AccessExMain{
public static void main(String[] args) {
AccessEx ae = new AccessEx();
//System.out.println(ae.a); // private 접근 불가
System.out.println(ae.b);
System.out.println(ae.c);
System.out.println(ae.d);
}
}
각 접근 제한자 사용 - 다른 패키지
package chapter06;
import chapter07.AccessEx;
public class AccessExMain{
public static void main(String[] args) {
AccessEx ae = new AccessEx();
//System.out.println(ae.a); // private 접근 불가
System.out.println(ae.b); // protected 접근 불가
System.out.println(ae.c); // default 접근 불가
System.out.println(ae.d);
}
}
싱글톤 singletone 기법(패턴)
- 클래스의 인스턴스를 하나만 생성되도록 프로그래밍 하는 기법
- 생성자 private 접근제어, static 메서드를 통해 인스턴스 리턴
클래스 생성
package chapter07;
public class Singleton {
// static 변수
private static Singleton instance = new Singleton();
// 생성자에 private 접근 제한자
private Singleton() {
System.out.println("객체 생성");
}
// static 메서드
public static Singleton getInstance() {
System.out.println("객체 리턴");
return instance;
}
}
클래스 사용
package chapter07;
public class SingletonMain {
public static void main(String[] args) {
//Singleton s = new Singleton(); // 에러 발생
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
Singleton s3 = Singleton.getInstance();
System.out.println(s1); // 동일 주소
System.out.println(s2); // 동일 주소
System.out.println(s3); // 동일 주소
}
}
'Programing > JAVA' 카테고리의 다른 글
상속 INHERITANCE_Part1 (2) | 2022.03.03 |
---|---|
클래스 CLASS_Part4 (0) | 2022.03.02 |
클래스 CLASS_Part2 (0) | 2022.03.02 |
클래스 CLASS_Part1 (0) | 2022.03.02 |
배열 ARRAY (2) | 2022.02.28 |