nme.kr

Ch.07 클래스

클래스와 객체

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package chapter07;
 
public class MemberMain {
 
    public static void main(String[] args) {
         
        Member m = new Member();
        Member m2 = new Member();
         
        if (m == m2) {
            System.out.println("m개체와 m2객체는 같다.");
        } else {
            System.out.println("m개체와 m2객체는 같지 않다.");
        }
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package chapter07;
 
public class MemberMain2 {
 
    public static void main(String[] args) {
         
        MemberMain2 m = new MemberMain2();
        MemberMain2 m2 = new MemberMain2();
         
        if (m == m2) {
            System.out.println("m개체와 m2객체는 같다.");
        } else {
            System.out.println("m개체와 m2객체는 같지 않다.");
        }
    }
 
}

클래스의 구조

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package chapter07;
 
public class Car {
 
    // 필드
    String color;
    String company;
    String type;
     
    // 메서드
    public void go() {
        System.out.println("전진하다.");
    }
    public void back() {
        System.out.println("후진하다.");
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package chapter07;
 
public class CarMain {
 
    public static void main(String[] args) {
         
        Car tico = new Car();
        Car pride = new Car();
         
        tico.color = "화이트";
        tico.company = "대우";
        tico.type = "경차";
         
        pride.color = "블랙";
        pride.company = "기아";
        pride.type = "소형";
         
        tico.go();
        pride.go();
        System.out.println(tico.color);
        System.out.println(tico.company);
        System.out.println(tico.type);
        System.out.println(pride.color);
        System.out.println(pride.company);
        System.out.println(pride.type);
         
    }
}

객체를 배열에 저장.

배열은 같은 자료형의 값을 담을 수 있기에 Car타입의 배열을 선언하면 여러 개의 Car 객체이 가능하다. 객체 역시 참조 자료형이기에 메모리 주소값을 참조한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package chapter07;
 
public class CarMain2 {
 
    public static void main(String[] args) {
         
        // Car 타입의 배열객체 생성
        Car[] cars = new Car[3];
         
        // 모든 인덱스에 new 연산자로 객체 생성 후 저장
        for (int i=0; i<cars.length; i++) {
            cars[i] = new Car();
            cars[i].color = "화이트";
            cars[i].company = "대우";
            cars[i].type = "경차";
        }
         
        System.out.println("0번 인덱스 color : "+cars[0].color);
        System.out.println("1번 인덱스 color : "+cars[1].color);
        System.out.println("2번 인덱스 color : "+cars[2].color);
         
        cars[0].color = "블랙"; // 0번 인덱스 객체의 color 필드에 "블랙" 대입
         
        System.out.println("0번 인덱스 color : "+cars[0].color);
        System.out.println("1번 인덱스 color : "+cars[1].color);
        System.out.println("2번 인덱스 color : "+cars[2].color);
         
    }
}

필드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package chapter07;
 
public class VarEx {
 
    public static void main(String[] args) {
         
        // 클래스 변수 사용
        System.out.println("Avante 제조사 : "+Avante.company);
         
        Avante a1 = new Avante();
        Avante a2 = new Avante();
         
        // 인스턴스 변수의 값 변경
        a1.color = "화이트";
        a2.color = "블랙";
         
        // 인스턴스 변수 출력
        System.out.println("a1 색상 : "+a1.color);
        System.out.println("a2 색상 : "+a2.color);
         
        // 클래스 변수를 인스턴스 객체로 출력
        System.out.println("a1 제조사 : "+a1.company);
        System.out.println("a2 제조사 : "+a2.company);
         
        // 클래스 변수의 값 변경
        a1.company = "기아";
         
        // 클래스 변수의 값 변경 후 클래스변수와 인스턴스변수 출력
        System.out.println("Avante 제조사 : "+Avante.company);
        System.out.println("a1 제조사 : "+a1.company);
        System.out.println("a2 제조사 : "+a2.company);
         
     
    }
     
     
}
 
class Avante {
     
    static String company = "현대"; // 클래스 변수
    String color;   // 인스턴스 변수
     
}

변수의 범위

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package chapter07;
 
public class LocalValEx {
 
    public static void main(String[] args) {
     
        Local local = new Local();
         
        System.out.println(local.name); // null
         
        local.process();
        System.out.println(local.name); // 홍길동
         
        local.printAge1();
        local.printAge2();
         
        // for문 블록 내에서의 변수 선언
        for (int i=0; i<10; i++) {
            int temp = 0;
            temp += i;
        }
         
        //System.out.println(temp); // 에러
 
    }
 
}
 
class Local {
     
    String name;
     
    void process() {
        name = "홍길동";
    }
     
    void printAge1() {
        int age = 20; // 지역변수
        System.out.println(age);
    }
     
    void printAge2() {
        int age = 30; // 지역변수
        System.out.println(age);
    }
     
}

메서드

매개 변수 선언

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package chapter07;
 
public class ParamEx {
 
    public static void main(String[] args) {
         
        Param p = new Param();
        p.add(10,5);
        //p.add("10", "5"); //에러
         
        p.add2(10, 5);
 
    }
 
}
 
class Param {
     
    void add(int x, int y) {
        int z = x + y;
        System.out.println(z);
    }
     
    void add2(double x, double y) {
        double z = x + y;
        System.out.println(z);
    }
}

리턴값

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package chapter07;
 
public class ReturnEx {
     
    public static void main(String[] args) {
         
        Return obj = new Return();
         
        String name = obj.getName();
        int age = obj.getAge();
         
        System.out.println(name);
        System.out.println(age);
        System.out.println(obj.getName());
        System.out.println(obj.getAge());
         
    }
 
}
 
 
class Return {
     
    String getName() {
        return "홍길동";
    }
     
    int getAge() {
        return 30;
    }
}

return문으로 메서드를 중지

return문은 두 개 이상 쓸 수 없다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package chapter07;
 
public class ReturnEx2 {
     
    public static void main(String[] args) {
         
        Return2 obj = new Return2();
         
        obj.getTest(0);
        obj.getTest(1);
         
        System.out.println(obj.getName(0));
        System.out.println(obj.getName(1));
         
    }
 
}
 
 
class Return2 {
     
    void getTest(int type) {
        System.out.println("getTest() 메서드 시작");
         
        if (type == 1) {
            return;
        }
         
        System.out.println("getTest() 메서드 끝");
    }
     
    String getName(int type) {
         
        if (type == 1) {
            return "";
        }
         
        return "홍길동";
    }
     
    String getAge(int type) {
         
        return "";
         
        //return "홍길동"; // 에러발생
    }
}

메서드의 실행(호출)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package chapter07;
 
public class MethodCall {
 
    public static void main(String[] args) {
         
        // 직접 실행
        Method.printName();
         
        // 객체를 생성해서 실행
        Method m = new Method();
        m.printEmail();
 
    }
 
}
 
class Method {
     
    static void printName() {
        System.out.println("printName() 실행");
    }
     
    void printEmail() {
        System.out.println("printEmail() 실행");
         
        printId(); // 다른 메서드 실행
    }
     
    void printId() {
        System.out.println("printId() 실행");
    }
}

메서드의 실행순서

Stack형 자료구조 - 가장 나중에 들어온 데이터가 가장 먼저 출력되는 자료구조

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package chapter07;
 
public class MethodOrder {
 
    public static void main(String[] args) {
         
        MethodEx me = new MethodEx();
         
        me.one(); // 메서드 실행
 
    }
 
}
 
class MethodEx {
     
    void one() { // 1.
        two();
        System.out.println("one");
    }
     
    void two() { // 2.
        three();
        System.out.println("two");
    }
     
    void three() { // 3.
        System.out.println("three");
    }
}

메서드의 중첩

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package chapter07;
 
public class MethodEx2 {
 
    public static void main(String[] args) {
         
        System.out.println(divide(pow(add(3,3))));
 
    }
     
    static int add(int x, int y) {
        return x + y;
    }
     
    static int pow(int x) {
        return x * x;
    }
     
    static int divide(int x) {
        return x / 2;
    }
     
 
}

메서드 오버로딩

클래스 내에 같은 이름의 메서드를 여러개 생성하는 것. 매개변수를 다양하게 입력 받기 위해 존재하며, 매개변수의 자료형, 개수, 순서 중에 하나 이상은 다르게 입력되어야 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package chapter07;
 
public class Overloading {
 
    public static void main(String[] args) {
         
        Operator op = new Operator();
         
        System.out.println(op.multiply(4, 3));
        System.out.println(op.multiply(4.5, 3.5));
        System.out.println(op.multiply(4, 3.5));
        System.out.println(op.multiply(4.5, 3));
 
    }
 
}
 
class Operator {
     
    int multiply(int x, int y) {
        System.out.println("(int, int)");
        return x * y;
    }
     
    double multiply(double x, double y) {
        System.out.println("(double, double)");
        return x * y;
    }
     
    double multiply(int x, double y) {
        System.out.println("(int, double)");
        return x * y;
    }
     
    double multiply(double x, int y) {
        System.out.println("(double, int)");
        return x * y;
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package chapter07;
 
public class Overloading2 {
 
    public static void main(String[] args) {
         
        System.out.println(1);
        System.out.println(5.5);
        System.out.println((long)100);
        System.out.println("홍길동");
        System.out.println('a');
        System.out.println(true);
        System.out.println(new Overloading2());
        System.out.println(new int[5]);
         
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package chapter07;
 
public class Overloading2 {
 
    public static void main(String[] args) {
         
        System.out.println(1);
        System.out.println(5.5);
        System.out.println((long)100);
        System.out.println("홍길동");
        System.out.println('a');
        System.out.println(true);
        System.out.println(new Overloading2());
        System.out.println(new int[5]);
         
    }
 
}

생성자

- 객체의 초기화를 위해 존재한다.

형태

1
Member member = new Member();

변수 초기화

에러 발생

Student(String name, int grade, String department)생성자가 정의되면 Student()생성자는 사용할 수 없으므로 직접 정의해 주어야 함.

생성자 오버로딩

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package chapter07;
 
public class Student {
 
    // 필드
    String name; // 학생명
    int grade; // 학년
    String department; // 학과
     
    // 1번 생성자
    Student() {
         
    }
     
    // 2번 생성자
    Student(String n) {
        name = n;
    }
     
    // 3번 생성자
    Student(String n, int g) {
        name = n;
        grade = g;
    }
     
    // 4번 생성자
    Student(String n, int g, String d) {
        name = n;
        grade = g;
        department = d;    
    }
     
    // 학과와 학년을 매개변수로 받는 생성자 (에러 발생)
//  Student(String d, int g) {
//      department = d;    
//      grade = g;
//  }
}

새로운 객체 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
package chapter07;
 
public class StudentMain {
 
    public static void main(String[] args) {
         
        Student stu1 = new Student(); // 1번 생성자
        Student stu2 = new Student("홍길동"); // 2번 생성자
        Student stu3 = new Student("홍길동", 4); // 3번 생성자
        Student stu4 = new Student("홍길동", 4, "소프트웨어공학");
         
    }
}

this 생성자

객체자신

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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;
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package chapter07;
 
public class Car2Main {
 
    public static void main(String[] args) {
        Car2 c1 = new Car2();
        Car2 c2 = new Car2("중형차");
        Car2 c3 = new Car2("현대", "대형차");
        Car2 c4 = new Car2("black", "기아", "화물차");
         
        System.out.println("c1 = "+c1);
        System.out.println("c2 = "+c2);
        System.out.println("c3 = "+c3);
        System.out.println("c4 = "+c4);
 
    }
 
}

초기화 블록

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package chapter07;
 
public class InitEx {
 
    // 생성자
    InitEx() {
        System.out.println("생성자 호출");
    }
 
    //static 초기화블럭
    static {
        System.out.println("클래스 초기화 블럭 실행");
    }
     
    // 인스턴스 초기화 블럭
    {
        System.out.println("인스턴스 초기화 블럭 실행");
    }
 
    public static void main(String[] args) {
        System.out.println("main 메서드시작");
        System.out.println("main init1 객체 생성");
        InitEx init1 = new InitEx();
        System.out.println("main init2 객체 생성");
        InitEx init2 = new InitEx();
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package chapter07;
 
public class InitEx2 {
 
    // static 변수
    static int sVar;
    // static 메서드
    static void sMethod() {
         
    }
     
    // 인스턴스 변수
    int var;
    // 인스턴스 메서드
    void method() {
         
    }
 
    //static 초기화블럭
    static {
        sVar = 0; // static 변수
        sMethod(); // static 메서드
         
        // 에러
        //var = 0; // 인스턴스 변수
        //method(); // 인스턴스 메서드
    }
     
    // static 메서드
    static void sMethod2() {
         
        // 에러
        //this.sVar = 0; // static 변수
        //this.sMethod(); // static 메서드
    }
     
 
}

패키지

1
2
3
4
5
6
7
8
package chapter07.test;
 
public class TestPackage {
 
    public void method() {
        System.out.println("chapter.test 패키지의 TestPackage 클래스");
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
package chapter07;
 
public class PackageEx {
 
    public static void main(String[] args) {
         
        chapter07.test.TestPackage test = new chapter07.test.TestPackage();
        test.method();
         
    }
     
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package chapter07;
 
import chapter07.test.TestPackage;
 
public class PackageEx2 {
 
    public static void main(String[] args) {
         
        TestPackage test = new TestPackage();
        test.method();
         
    }
     
}

1
2
3
4
import chapter07.test.TestPackage;
import chapter07.test.TestPackage2;
import chapter07.test.*; //해당패키지의 모든 클래스를 import
import chapter07.*; // chapter07 패키지 안에 있는 모든 클래스 사용, test 패키지는 미포함

접근 제한자

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package chapter07.test;
 
public class ClassA {
     
    public static void main(String[] args) {
     
        ClassB cb = new ClassB();
        cb.print();
         
    }
     
    public void print() {
        System.out.println("여기는 ClassA");
    }
     
}
 
class ClassB {
    void print() {
        System.out.println("여기는 ClassB");
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package chapter07.test.test2;
 
import chapter07.test.*;
 
public class ClassC {
    public static void main(String[] args) {
         
        ClassA ca = new ClassA();
        ca.print();
         
        //ClassB cb = new ClassB(); // 접근제한자 때문에 에러
         
         
    }
}

싱글톤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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;
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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();
 
    }
 
}

final

final 변수, 상수

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package chapter07;
 
public class FinalEx {
 
    public static void main(String[] args) {
         
        Final f = new Final();
        //f.number = 200; // 에러
    }
     
}
 
class Final {
    final int number;
     
    Final() {
        number = 100;
    }
}

상수(static final)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package chapter07;
 
public class ConstantEx {
     
    static final double CARD_COMMISSION = 1.5;
 
    public static void main(String[] args) {
         
        System.out.println("원주율 : "+Math.PI);
        System.out.println("카드 수수료율 : "+CARD_COMMISSION);
        // CARD_COMMISSION = 1.8; // 에러
 
    }
 
}