본문 바로가기
2022-2/자바

객체와 클래스

by 철없는민물장어 2022. 10. 11.
728x90

생성자

생성자가 선언되지 않은 경우에는 기본 생성자를 컴파일러가 자동으로 만들어 줌.

(하나라도 생성자가 선언된 경우는 기본생성자가 생기지않음)

 

this

클래스 내에서 메소드 작성할 때

인자로 받는 변수이름과 클래스 멤버변수의 변수명이 같을 때

멤버변수를 this.변수명 으로 써서 구별함.

 

소멸자

자바에서는 가비지컬렉터가 있어 소멸자가 없음


this()

같은 클래스 내의 다른 생성자 호출

class Box{
	int width;
    int height;
    int depth;
	public Box(){
    	width=1;
        height=1;
        depth=1;
        }
    public Box(int w){
    	width = w;
        height =1;
        depth = 1;}
    public Box(int w, int h, int d){
    	width = w;
        height = h;
        depth = d;
        }
 }

이런 코드를 

class Box{
	int width;
    int height;
    int depth;
    
	public Box(){
    	this(1,1,1);
        }
    public Box(int w){
    	this(w,1,1);
        }
    public Box(int w, int h){
    	this(w,h,1);
        }
    public Box(int w, int h, int d){
    	width = w;
        height = h;
        depth = d;
        }
 }

이렇게 코드를 줄일 수 있다.

this는 클래스 내의 가장 마지막 생성자를 호출한다.

 


접근 제어 수식어

  • public : 클래스와 인터페이스 외부에서 사용 가능함
  • private : 클래스 내에서만 사용 가능함
  • protected : 같은 패키지 안에서 사용가능, 다른 패키지에서는 상속관계인 경우만 사용가능
  • 없는 경우: 같은 패키지 안에서 사용가능

 


메소드

  • final 
  • abstract
  • synchronized

static의 사용

 

클래스 메소드는 클래스이름(또는 객체이름).메소드(매개변수)로 접근가능.

객체를 생성하지 않아도 메모리에 올라가서 사용가능

 

전역 변수와 전역 함수를 만들 때 활용할 수 있다.

class Math{
	staic int abs(int a);
    static int max(int a,int b);
    .
    .
    }

이런 Math클래스가 있다고 할 때, 메소드를 이용하기 위해 매번 객체를 생성하기는 불편하다.

메소드를 static으로 선언했기 때문에, 객체를 생성하지 않고

Math.max(2,4); 이런식으로 사용할 수 있다.

 

static 메소드 주의사항

static 메소드는 static 멤버만 접근할 수 있다.

class staticMethod{
	int n;
    static int m;
    
    void f1(int x) {m = x;}
    static void f2(int x) {n=x;};//오류
    }

또한 static 메소드에서는 this키워드를 사용할 수 없다.

내 객체가 없는드ㅔ 무슨 멤버변수에 접근을?

 

class Calc1011{
	
	static int abs(int x) {
		return (x>0)?x:(-1*x);
	}
	static int max(int a,int b) {
		return (a>b)?a:b;
	}
	static int min(int a,int b) {
		return (a<b)?a:b;
	}
}

public class CalcEx {

	public static void main(String[] args) {
		System.out.println(Calc1011.abs(5));
		System.out.println(Calc1011.max(2, 9));
		System.out.println(Calc1011.min(-3,-4));
	}

}

static을 사용하는 예제.


 

728x90

'2022-2 > 자바' 카테고리의 다른 글

3. 객체지향  (0) 2022.10.20
오버로딩  (0) 2022.10.20
3장 클래스,캡슐화, 다형성  (0) 2022.10.09
자바 - 명령행 매개변수, 클래스, 클래스 상속, 클래스 배열  (0) 2022.09.27
자바 - 객체 복사 참고사항  (0) 2022.09.25

댓글