티스토리 뷰

목차



    반응형
    생성자
    생성자 오버로드
    static 변수
    static 메소드
    변수 유효 범위

    생성자

    인스턴스를 생성할 때 new와 함께 사용

    생성자 이름은 클래스와 이름과 동일

    Student s1 = new Student(); // 생성자

    생성자는 멤버 변수, 메소드와 마찬가지로 클래스에서 정의

    class Student{
        int number;
        int score;
        String name;
        public Student(){} // 생성자
        void studey(){
            System.out.println("Studying");
        }
    }

    생성자를 선언하지 않아도 자동으로 만들어진다.

    class Student{
        int number;
        int score;
        String name;
        //public Student(){} 기본 생성자
        void studey(){
            System.out.println("Studying");
        }
    }

    생성자 구현

    생성자에 인자가 필요하면 명시적으로 구현할 수 있음(예, 학번)

    인스턴스가 생성되는 시점에 수행할 작업이 있는 경우 생성자를 활용

    생성자에 인자를 넘겨 멤버 변수를 초기화하는 등 특정한 작업을 수행

    class Student {
        String name;
        
        public Student(String pname) {
            name = pname;
            System.out.println("Student 인스턴스 생성");
        }
    }

    this

    인스턴스 "자기 자신"을 나타내는 예약어 : this

    // 멤버 변수 name을 매개변수 name으로 초기화
    
    class Student {
        String name;
        
        public Student(String name){
            name = name; // 둘 다 매개변수 name으로 인식
        }
    }
    
    // this를 이용한 멤버 변수 초기화
    
    class Student {
        String name;
        
        public Student(String name) {
            this.name = name; // this.name은 멤버 변수, name은 매개변수를 각각 가리킨다.

    매개변수와 멤버 변수의 이름이 같지 않다면 this를 쓰지 않아도 상관없다.

    class Student {
        String name;
        
        public Student(String pname) {
            name = pname;
            System.out.println("Student 인스턴스 생성");
        }
    }

    복잡한 소스코드에서 변수가 많아지면 관리하기 힘든 경우가 발생한다.

    멤버 변수와 매개 변수에 같은 이름을 부여하고 this로 구분하면 관리에 용이하다.

    생성자 오버로드

    생성자를 여러 개 선언할 수 있다.

    class Student {
        String name;
        int height;
        int weight;
        
      	
        public Student() {} // 멤버 변수 초기화1
        public Student(String name) {
            this.name = name; 
        } // 멤버 변수 초기화2
        public Student(String name, int height, int weight) {
            this.name = name;
            this.height = height;
            this.weight = weight;
        } // 멤버 변수 초기화3
        
        Student s = new Student(); // 멤버 변수 초기화1
        Student s = new Student("Java"); // 멤버 변수 초기화2
        Student s = new Student("Java", 177, 77); // 멤버 변수 초기화3

    이와 같이 필요에 따라 여러 개를 만들 수 있다.

     

    static 변수

    static 키워드

    static 키워드는 변수와 메소드 앞에 붙일 수 있다.

    public class Student{
        static int number;
        static void study(){
            System.out.println("공부");
        }
    // 모양과 숫자는 플레잉 카드마다 다르지만 너비와 높이는 동일
    public class Card{
        static int width = 10;
        static int height = 16;
        String shape;
        int number;
    }

    프로그램이 실행될 때 인스턴스 생성과 상관없이 먼저 생성된다.

    Card card1 = new Card();
    Card card2 = new Card();
    
    System.out.println(card1.widdth); // 10
    card1.width = 20;
    System.out.println(card2.width); // 20
    Card.width = 35;
    System.out.println(card.width); // 35
    
    // static 변수의 값이 공유됨을 확인

    static 변수는 인스턴스와는 완전히 별개이며 인스턴스가 생성되지 않아도 사용할 수 있다.

    클래스에 속해 한 번만 생성되는 변수 이를 여러 인스턴스가 공유하는 클래스 변수라고도 한다.

    Card card1 = new Card();
    Card card2 = new Card();
    
    card1.width = 20;
    System.out.println(card1.width);
    // 바람직하지 않음
    Card.width = 35;
    System.out.println(Card.width);
    //static 변수는 클래스 이름으로 참조해야 한다.

    static 메소드

    static 변수와 마찬가지로 static 메소드 또한 존재

    public class Main {
        public static void main(String[] args) {
        // 대표적 예시
        }
    }

    static 변수를 이용하여 값을 반환하는 예시

    public class Card {
        static ine getArea() {
            return width * height;
        }
    }

    static 메소드에서 멤버 변수를 사용할 수 없다.

    public class Card {
        static int getCardValue() {
            return shape + number; // Error
        }
    }

    멤버 변수는 인스턴스를 생성한 후에 사용 가능

    static 메소드는 인스턴스를 생성하지 않아도 사용 가능

     

    static 메소드의 사용

    인스턴스를 생성할 필요 없이 클래스 이름으로 호출 가능

    인스턴스를 만들 필요가 없을 때 static 메소드면 충분하다.

    static 메소드만 모여 있는 클래스를 Util 클래스라고 부른다.

     

    변수 유효 범위

    public class Card {
        static int width = 10; // static 변수
        int number;           // 멤버 변수
        int drawCardNumber() {
            int pnumber;      // 지역 변수
            pnumber = getRandomInt(1, 13);
            return pnumber;
        }
    }

    지역 변수

    메소드 내부에 선언 메소드가 반환될 때 메모리에서 제거된다.

     

    멤버 변수

    인스턴스가 생성될 때 생성

    인스턴스가 더 이상 쓰이지 않을 때 제거된다.(Garbage collection)

     

    static 변수

    프로그램을 실행할 때 인스턴스 생성과 무관하게 처음부터 생성

    프로그램이 끝날 때 삭제

     

    각각의 특성을 이해하고 사용하는 것이 중요

    반응형