100일 챌린지/빅데이터기반 인공지능 융합 서비스 개발자

Day04 - Package와 생성자 사용하기

ksyke 2024. 7. 25. 14:02

목차

    클래스

    • 소스 코드의 이름이 달라도 클래스의 명이 같게 되면 컴파일 시 클래스 파일이 덮어쓰게 되거나 에러가 나올 수 있다.
    • 같은 클래스명을 사용할 수 package를 사용해 디렉토리를 구분짓는다.
    • 패키지로 디렉토리를 구분지어도 컴파일 후 클래스 파일을 실행시킬 수 없는것을 확인 할 수 있다.

    -> 이럴땐 파일이 어디 있는지 명시해 주어야 한다.

    여기서 'one'은 패키지 이름이다.

    패키지란

    클래스들이 위치하는 경로를 지정하는 것.

    패키지와 메모리

    • 클래스 명이 같은 클래스를 특정할 때는 숨겨져 있는 패키지 이름을 명시하면 된다.
    public class Ex03 {
        public static void main(String[] args) {
            double customRand = Math.random(); // 사용자가 만든 random 클래스
            System.out.println(customRand);
    
            double javaRand = java.lang.Math.random(); // 자바 안에 존재하고 있는 random 클래스
            System.out.println(javaRand);
        }
    }
    class Math{
        public static double random(){
            return 1.0;
        }
    }

    -> 숨겨져 있는 패키지 이름들은 컴파일 시 자동으로 붙여져서 컴파일된다.(javac.exe에서 작동) 생략된 패키지 이름은 소스코드 내에서 찾고, java.lang에서 찾은 후 그곳에도 없으면 에러를 띄운다.

    필드와 메모리

    • 클래스와 마찬가지로 같은 클래스명을 가질 경우 패키지명을 명시하면 된다.
    public class Ex03 {
        public static void main(String[] args) {
            double customPi = Math.PI;
            System.out.println(customPi);
    
            double javaPi = java.lang.Math.PI;
            System.out.println(javaPi);
        }
    }
    class Math{
        public static double PI = 2.14;
    }

    생성자

    • 객체의 생성 시점에 하고자 하는 일을 명세한다.
    • 생성자코드 생략시 디폴트 생성자를 자동생성한다.
      • 디폴트 생성자: public 클래스명(){}
      • public class Ex04 { public Ex04(){ // 생략된 생성자 System.out.println("객체가 생성됨"); System.out.println("생성자"); } public void func01(){ System.out.println("실행"); } public static void main(String[] args) { Ex04 me; me = new Ex04(); me.func01(); } }
    • 매개변수를 받는 생성자를 만들 경우 디폴트로 생성자를 만들지 않는다. (디폴트 생성자를 따로 명시해야 한다.- 생성자 오버로드)

    상수형 변수

    final을 사용해 변수를 상수처럼 사용한다.

    final int b;

    여기서 b의 값을 바꾸려고 하면 다음의 에러가 나온다.

    Ex05.java:11: error: variable b might already have been assigned
            b = 2000;
            ^
    1 error

    멤버 필드의 상수형 변수

    public final static int su2 = 2222;
    • 위와 같이 멤버 필드에 상수형 변수를 만들 수 있다.
    • 이때, 변수의 초기값을 명시하지 않으면 java에서 에러가 난다.
    Ex05.java:5: error: variable su2 not initialized in the default constructor
        public final static int su2;
                                ^
    1 error

    non-static의 경우

    • 생성자에서 상수형 변수의 초기값을 명시해 주면 컴파일이 가능하다.
    public class Ex05 {
        public final int su3;
    
        public Ex05(){
            su3 = 3333;
        }
    
        public static void main(String[] args) {
            Ex05 me = new Ex05();
            System.out.println(me.su3);
        }
    }

    다른 클래스파일 사용하기 (.jar 사용)

    Car.java에 있는 클래스를 Ex06에서 사용하고 싶을 때:

    <cmd>
    javac -encoding utf8 -d dist Car.java
    cd dist
    jar -cf Car.jar . 
    cd ../
    javac -encoding utf8 -d dist -cp C:/workspace/Day04/dist/Car.jar Ex06.java 
    java -classpath dist com.Day04.Ex06

    생성자 사용하기

    class Ex07{
        public static void main(String[] args) {
            func01();
    
            Ex07 me = new Ex07();
            me.func02(); // f3
    
            Ex07 you = new Ex07();
            System.out.println(me == you); // false
            Ex07 me2 = me;
            System.out.println(me == me2); // true
    
        }
        public static void func01(){
        }
        public void func02(){
            this.func03();
        }
        public void func03(){
            System.out.println("f3");
        }
    }
    • meme2는 객체가 같기 때문에 같은 레퍼런스이다.
    • static에서는 this가 존재하지 않고 오직 non-static에서만 this가 존재한다.
    • static에서 this를 사용하기 위해서는 필드에 객체를 생성하고 사용한다.
    class Ex07{
        static Ex07 you = new Ex07();
        public static void main(String[] args) {
        ...
        }
    }

    static에서 static을 호출할 때

    • [패키지.클래스명.]메서드명

    static에서 non-static을 호출할 때

    • 참조변수.메서드명

    non-static에서 static을 호출할 때

    • [패키지.클래스명.]메서드명

    non-static에서 non-static을 호출할 때

    • `[this.]메서드명

    지역(local) 변수와 전역(global) 변수

    • 우선순위: 지역 > 전역
    public class Ex08 {
        // 전역(global) 변수
        public static int a = 9999;
        public int b = 8888;
    
        public static void main(String[] args) {
            int a = 1111; // 지역(local) 변수
            int b = 2222;
            System.out.println(a);
            // 전역 변수 사용
            System.out.println(Ex08.a);
            // 전역의 non-static 변수 사용
            Ex08 me = new Ex08();
            System.out.println(me.b);
    
            me.func01();
        }
    
        public void func01(){
            int a = 1000;
            int b = 2000;
            System.out.println(a);
            // 전역의 non-static 변수 사용
            System.out.println(this.b);
        }
    }

    생성자 공통작업 작성하기

    public class Ex09 {
        public Ex09(){
            System.out.print("생성자");
        }
    
        public Ex09(int a){
            this();
            System.out.println(" a = " + a);
        }
    
        public static void main(String[] args) {
            new Ex09();
            System.out.println();
            new Ex09(1111);
        }
    }
    • this();는 항상 생성자 제일 상단에 위치해야 한다.
    • 중복 사용되는 생성 코드는 디폴트 생성자에서 불러올 수 있다.
    public class Ex09 {
        public Ex09(){
            // super(); // 생략된 객체 생성 코드 
            // System.out.print("생성자");
            this(1234);
        }
    
        public Ex09(int a){
            // this();
            System.out.println(" a = " + a);
        }
    
        public static void main(String[] args) {
            new Ex09();
            System.out.println();
            new Ex09(4321);
        }
    }
    public String model;
    public String color;
    public int speed = 0;
    public final int MAX;
    
    public Car(){
        this("회", "아반떼", 80)
    }
    public Car(String color){
        this(color, "소나타", 95)
    }
    public Car(String color, String model){
        this(color, model, 100)
    }
    public Car(String color, String model, int max){
        this.color = color;
        this.model = model;
        this.MAX = max;
    }
    • this.은 전역 변수를 호출하는 코드
    • this()는 생성자 내부에서 다른 생성자를 호출하는 코드

    Day04.7z
    0.01MB