상속에 의미

● 새로운 클래스를 정의 할 때 이미 구현된 클래스를 상속(inheritance) 받아서 속성이나 기능을 확장하여 클래스를 구현함

● 이미 구현된 클래스보다 더 구체적인 기능을 가진 클래스를 구현해야 할때 기존 클래스를 상속함

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
package ch10;
 
public class A {
    String name; 
    int height; 
    int weight; 
    int age;
    
    // 코드 테스트 
    public static void main(String[] args) {
        
        C myC = new C(); 
        myC.age = 100
        System.out.println(myC.age);
        
    }
// end of A class
 
 
 
class B {
    String name; 
    int height; 
    int weight; 
    int age;
    
    int level; 
    String nicName; 
    
// end of B class 
 
class C extends A {
    
    String phone; 
    
// end of C class
cs
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
```java
package ch10;
 
public class A {
    String name; 
    int height; 
    int weight; 
    int age;
    
    // 코드 테스트 
    public static void main(String[] args) {
        
        C myC = new C(); 
        myC.age = 100
        System.out.println(myC.age);
        
    }
// end of A class
 
class B {
    String name; 
    int height; 
    int weight; 
    int age;
    
    int level; 
    String nicName; 
    
// end of B class 
 
class C extends A {
    
    String phone; 
    
// end of C class
```
cs

상속에 대한 개념 메서드 오버 라이딩 → 재정의 메서드 오버 로딩 → 같은 메서드 이름을 사용할 수 있게 한다 (매개변수로 구분 가능) 접근 제어 지시자 의미 확인 → protected

'자바' 카테고리의 다른 글

추상 클래스의 응용 - 템플릿 메서드 패턴  (0) 2023.02.16
추상 클래스(abstract class)  (0) 2023.02.16
다형성  (0) 2023.02.16
Static 변수  (0) 2023.02.15
this가 하는 일  (0) 2023.02.14

다형성(polymorphism) 이란?

● 하나의 코드가 여러 자료형으로 구현되어 실행되는 것

● 같은 코드에서 여러 다른 실행 결과가 나옴

● 정보은닉, 상속과 더불어 객체지향 프로그래밍의 가장 큰 특징 중 하나임

● 다형성을 잘 활용하면 유연하고 확장성있고, 유지보수가 편리한 프로그램을 만들수 있음

다향성

학습 목표 다형성 : 다양한 형태로 데이터 타입을 바라볼 수 있다 업캐스팅 상태 : 부모 타입으로 자식 클래스를 생성해서 담을 수 있다. 다운 캐스팅 : 강제 형 변환→ 자식 클래스 명시 하는 것 보통 반복문과 함께 쓰이는 instaceof 연산자를 이해 하자

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
package ch11;
 
public class Animal {
    
    public void move() {
        System.out.println("동물이 움직입니다.");
    }
    
    public void eating() {
        System.out.println("먹이를 먹습니다.");
    }
    
}
 
class Human extends Animal {
    
    @Override
    public void move() {
        System.out.println("사람이 두발로 걷습니다");
    }
    
    @Override
    public void eating() {
        System.out.println("밥을 먹습니다");
    }
    
    public void readBooks() {
        System.out.println("책을 읽습니다");
    }
}
 
class Tiger extends Animal {
    
    @Override
    public void move() {
        System.out.println("호랑이가 네 바로 걸어요");
    }
    
    public void hunting() {
        System.out.println("호랑이가 사냥을 합니다");
    }
}
cs
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 ch11;
 
public class AnimalMainTest2 {
 
    public static void main(String[] args) {
 
        // Human human = new Human();
        // 다형성을 적용하게 된다면 부모타입으로 데이터 타입을 선언 할수있고
        // 실제 메모리에 올라가는 객체를 다형이 적용되는 클래스를 인스턴스화 할수있다
        Animal animalH = new Human();
        Animal animalT = new Tiger();
 
        Animal[] arrAnimal = new Animal[10];
        arrAnimal[0= animalH;
        arrAnimal[1= animalT;
 
        for (int i = 0; i < arrAnimal.length; i++) {
            if (arrAnimal[i] != null) {
                arrAnimal[i].move();
                arrAnimal[i].eating();
 
            }
        }
 
    }
 
}
 
cs

다향성을 바탕으로 

랜덤 뽑기 게임!!!! 내가한거 굳 기분이 좋습니다

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package test01;
 
import java.util.Random;
import java.util.Scanner;
 
public class MainTest {
 
 
 
    public static void main(String[] args) {
 
        Toy toy1 = new CarToy();
        Toy toy2 = new BabiToy();
        Toy toy3 = new SwordToy();
        Toy toy4 = new End();
 
        Scanner sc = new Scanner(System.in);
        System.out.println("몇번 뽑으시겠습니까");
        int user = sc.nextInt();
        int count1 = 0;
        int count2 = 0;
        int count3 = 0;
        int[] ranNumbers = new int[50];
        // 0 ~ 9
        for (int i = 0; i < user; i++) {
            ranNumbers[i] = randomNumber();
            // System.out.println(ranNumbers[i]);
            if (ranNumbers[i] == 11) {
                System.out.println(ranNumbers[i] + " 번을 뽑으셨습니다 " + toy1.name + " 입니다 ");
                count1++;
            } else if (ranNumbers[i] == 37) {
                System.out.println(ranNumbers[i] + " 번을 뽑으셨습니다 " + toy2.name + " 입니다 ");
                count2++;
            } else if (ranNumbers[i] == 15) {
                System.out.println(ranNumbers[i] + " 번을 뽑으셨습니다 " + toy3.name + " 입니다 ");
                count3++;
            } else {
                System.out.println(toy4.name);
            }
        }
        System.out.println("====================");
        if(count1  > 0) {
            System.out.println(toy1.name+"이 "+count1 + " 번 당첨 되었습니다");
        }
        if(count2  > 0) {
            System.out.println(toy2.name+"이 "+count2 + " 번 당첨 되었습니다");
        }
        if(count3  > 0) {
            System.out.println(toy3.name+"가 "+count3 + " 번 당첨 되었습니다");
        }
        // 사용자 입려값 받기
        //
 
    }// end of main
 
    // 랜덤 번호 하나 뽑기
    // 함수 : 랜덤
    public static int randomNumber() {
        Random random = new Random();
        return random.nextInt(45+ 1;
    }
 
}// end of class
 
cs
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 test01;
 
public class Toy {
 
    String name;
    public void showInfo() {
        System.out.println("상품명 : "+name);
    }
}
 
class End extends Toy{
    public End() {
        name = "꽝";
    }
}
class CarToy extends Toy{
    public CarToy() {
        name = "벤츠장난감";
    }
}
class BabiToy extends Toy{
    public BabiToy() {
        name = "바비인형";
    }    
}
class SwordToy extends Toy{
    public SwordToy() {
        name = "엑스칼리버";
    }
}
cs

 

'자바' 카테고리의 다른 글

추상 클래스(abstract class)  (0) 2023.02.16
상속  (0) 2023.02.16
Static 변수  (0) 2023.02.15
this가 하는 일  (0) 2023.02.14
객체와 객체간의 상호작용 정보은닉(infomation hiding)  (0) 2023.02.14

공통으로 사용하는 변수가 필요한 경우

1.여러 인스턴스가 공유하는 기준 값이 필요한 경우

2.학생마다 새로운 학번 생성

3.카드회사에서 카드를 새로 발급할때마다 새로운 카드 번호를 부여

4.회사에 사원이 입사할때 마다 새로운 사번이 필요한

5.은행에서 대기표를 뽑을 경우(2대 이상)

static 변수 선언과 사용하기

● 선언 방법 - static int serialNum;

● 인스턴스가 생성될 때 만들어지는 변수가 아닌, 처음 프로그램이 메모리에 로딩될 때 메모리를 할당

● 클래스 변수, 정적변수라고도 함

● 인스턴스 생성과 상관 없이 사용 가능하므로 클래스 이름으로 직접 참조

● 사용방법 - Student.serialNum = 100;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package ch08;
 
public class NumberPrinter {
 
    private int id;
    //private static int waitNumber;
    public static int waitNumber;
 
    // 생성자는 맨먼저 실행 되고 한번만 수행이 된다
    public NumberPrinter(int id) {
        this.id = id;
        this.waitNumber = 1;
    }
 
    // 번호 표를 출력 합니다.
    public void printWaitNumber() {
        System.out.println(" 대기 순번 " + waitNumber);
        waitNumber++;
    }
 
}
 
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package ch08;
 
public class MainTest2 {
//메인함수
    public static void main(String[] args) {
        //클래스 안에 맴버 변수를 사용할려면
        //반드시 먼저 메모리에 올려야 한다.
        
        
        //수행 요청 - 클래스이름.
        System.out.println(NumberPrinter.waitNumber);
        NumberPrinter.waitNumber++;
        NumberPrinter.waitNumber++;
        NumberPrinter.waitNumber++;
        System.out.println(NumberPrinter.waitNumber);
        
        //static 은문법적으로  class xxx {} 안 에 작성하지만 static 키워드를 가진녀석은
        //잠시 자리만 빌려서 문법만 쓸뿐 메모리를 사용하는 영역은 미리 뜨는 static 영역이다.
        
    }//end of main
 
}//end of class
 
cs

Static 변수 활용!!

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 ch08;
 
public class EmployeeMainTest {
//main
    public static void main(String[] args) {
        
        Employee employee1 = new Employee();
        employee1.setName("이순신");
        System.out.println(employee1.serialNum);
        
        Employee employee2 = new Employee();
        employee2.setName("홍길동");
        
        Employee employee3 = new Employee();
        employee3.setName("티모");
        
 
        //static 변수만 사용 하면
        //각각 객체가 가지는 상태값을 저장해야한다면
        System.out.println(Employee.serialNum);
        //맴버면수를 사용해야한다
        //이순신
        System.out.println(employee1.getEmployeeid());
        //홍길동
        System.out.println(employee2.getEmployeeid());
        //티모
        System.out.println(employee3.getEmployeeid());
    }//end of main
 
}//end of class
 
cs
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
48
49
package ch08;
 
/**
 * 
 * @author GGG static 변수와 맴버변수의 활용!!!!!
 */
public class Employee {
 
    public static int serialNum;
    private int employeeid;
    private String name;
    private String department;
 
    // 생성자를 호출한다는것은
    public Employee() {
        serialNum++;
        employeeid = serialNum;
    }
 
    public int getEmployeeid() {
        return employeeid;
    }
 
    public static int getSerialNum() {
        return serialNum;
    }
 
    public static void setSerialNum(int serialNum) {
        Employee.serialNum = serialNum;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getDepartment() {
        return department;
    }
 
    public void setDepartment(String department) {
        this.department = department;
    }
 
}
 
cs

'자바' 카테고리의 다른 글

상속  (0) 2023.02.16
다형성  (0) 2023.02.16
this가 하는 일  (0) 2023.02.14
객체와 객체간의 상호작용 정보은닉(infomation hiding)  (0) 2023.02.14
객체와 객체간의 상호작용 접근 제어 지시자(access modifier)  (0) 2023.02.14

● 인스턴스 자신의 메모리를 가리킴

● 생성자에서 또 다른 생성자를 호출 할때 사용

● 자신의 주소(참조값)을 반환 함

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
48
49
50
51
52
53
54
55
56
57
58
package ch07;
 
class Person {
 
    // this란 3가지
    // 1. 자기 자신으 가리킨다.
    // 2. 생성자에서 다른생성자를 호출할때 사용할수있다
    // 3. 자기자신의 주소(참조값,주소값)을 반환 시킬수 있다
 
    // 상태
    private String name;
    private int age;
    private String phone;
    private String gender;
 
    public Person(String name, int age) {
        // 자기 자신을 가리키는 this
        this.name = name;
        this.age = age;
    }
 
    // 생성자는 객체가 메모리에 올라갈때 제일 먼저 실행하는 코드이다
    public Person(String name, int age, String phone) {
        // new this();
        // 생성 자에서 다른생성자를 호출함
        this(name, age);
        this.phone = phone;
    }
 
    public Person(String name, int age, String phone, String gender) {
        this(name, age, phone);
        this.gender = gender;
    }
 
// 자기자신을 반환하는 this 는 빌더패턴을 만들어 낼수 있다.
    public Person getPerson() {
        // 3. 자기 자신의 주소값을 반환 시킬수 있다.
        return this;
    }
 
    public void showInfo() {
        System.out.println("이름 : " + name + ", 나이 : " + age);
    }
 
}// end of Person class
 
//XXX.java 파일 안에 여러개의 클래스 파일을 작성할수 있다
//단. XXX.java 파일 안에 public 을 가지는 클래스는 단하나만 선언 할수있다
//default 접근 제어 지시자 --> ch07에 있는 클래스 들은 사용가능
class PersonMainTest {
    // 메인함수
    // 메인함수는 메인함수 앞에 static 잠시 자리를 빌려서 사용한다.
    public static void main(String[] args) {
        Person person1 = new Person("홍길동"100);
        person1.showInfo();
 
    }// end of main
}// end of PersonMainTest class
cs

1.자기자신을 가르킨다

2.생성자에서 다른생성자를 호출할때 사용가능하다

3.자기자신의 주소(참조값,주소값) 반환 시킬수

정보 은닉

● private으로 제어한 멤버 변수도 public 메서드가 제공되면 접근 가능하지만 변수가 public으로 공개되었을 때보다 private 일때 각 변수에 대한 제한을 public 메서드에서 제어 할 수 있다.

캡슐화 (encapsulation)

정보 은닉을 활용한 캡슐화

● 꼭 필요한 정보와 기능만 외부에 오픈함

● 대부분의 멤버 변수와 메서드를 감추고 외부에 통합된 인터페이스만은 제공하여 일관된 기능을 구현 하게 함

● 각각의 메서드나 멤버 변수를 접근함으로써 발생하는 오류를 최소화 한다.

'자바' 카테고리의 다른 글

Static 변수  (0) 2023.02.15
this가 하는 일  (0) 2023.02.14
객체와 객체간의 상호작용 접근 제어 지시자(access modifier)  (0) 2023.02.14
객체지향 프로그래밍이란?  (0) 2023.02.14
생성자  (0) 2023.02.14

접근 제어 지시자 (accesss modifier)

▶ 클래스 외부에서 클래스의 멤버 변수, 메서드, 생성자를 사용할 수 있는지 여부를 지정하는 키워드

● private : 같은 클래스 내부에서만 접근 가능 ( 외부 클래스, 상속 관계의 클래스에서도 접근 불가)

● 아무것도 없음 (default) : 같은 패키지 내부에서만 접근 가능 ( 상속 관계라도 패키지가 다르면 접근 불가)

● protected : 같은 패키지나 상속관계의 클래스에서 접근 가능하고 그 외 외부에서는 접근 할 수 없음

● public : 클래스의 외부 어디서나 접근 할 수 있음

학생,버스,지하철 객체 상호작용

학생

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
package ch05;
 
public class Student {
 
    String name;
    int money;
    int time;
    int choose;
    
    public Student(String name,int money) {
        this.name = name;
        this.money = money;
    }
    
    //학생이 버스를 탄다
    public void takeBus(Bus targetBus) {
        //지역 선언
        System.out.println("targetBus 메서드 실행됨");
        //targetBus.showInfo();
        //요금을 넣어야한다
        targetBus.take(1_200);
        this.money -= 1_200;
    }
    
    //학생이 지하철을 탄다
    public void takeSubway(Subway targetSubway) {
        System.out.println("targetSubway 메서드 실행됨");
        targetSubway.take(1_250);
        this.money -= 1_250;
    }
    
    //상태창 보기
    public void showInfo() {
        System.out.println("학생의 이름은 :"+this.name);
        System.out.println("학생의 소지금 :"+this.money);
        System.out.println("---------------------");
        
    }
    
}
 
cs

버스

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 ch05;
 
public class Bus {
 
    int busNumber;
    int passengerCount;
    int money;
    
    public Bus(int busNumber) {
        this.busNumber = busNumber;
    }
    
    
    //기능
    public void take(int money) {
        this.money += money;
        this.passengerCount++;
    }
    public void showInfo() {
        System.out.println(this.busNumber + ": 번의 버스를 선택하셨습니다 다음버스는 3분 뒤입니다");
    }
    public void showInfo1() {
        System.out.println(this.busNumber + ": 번의 버스를 선택하셨습니다 다음버스는 5분 뒤입니다");
    }
    public void showInfo2() {
        System.out.println("버스번호 :"+this.busNumber);
    }
    
    
}
 
cs

지하철

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
package ch05;
 
public class Subway {
 
    int lineNumber;
    int passengerCount;
    int money;
    //생성자 - 리턴 타입없고 , 클래스 이름과 같다
    public Subway(int lineNumber) {
        this.lineNumber = lineNumber;
    }
    public void take(int money) {
        this.money +=money;
        this.passengerCount++;
    }
    public void showInfo() {
        System.out.println(this.lineNumber + "호선의 다음 열차는 6분뒤 입니다");
    }
    public void showInfo1() {
        System.out.println(this.lineNumber + "호선의 다음 열차는 4분뒤입니다");
    }
    public void showInfo2() {
        System.out.println("지하철 호선 :"+this.lineNumber);
    }
}
 
cs

메인 클래스

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
48
49
50
51
52
53
54
55
56
package ch05;
 
import java.util.Scanner;
 
public class MainTast2 {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // 객체 생성
        Student studentMin = new Student("김민우",47000);
        Bus bus1 = new Bus(169);
        Bus bus2 = new Bus(133);
        Subway subway1 = new Subway(1);
        Subway subway2 = new Subway(2);
        //1단계 = 사용해보기
//        bus1.showInfo();
//        bus2.showInfo();
//        subway.showInfo();    
        studentMin.showInfo();
        
        //2단계 = 실행의 흐름 만들어보기
        System.out.println("몇분에 집에서 나오셨습니까");
        studentMin.time = sc.nextInt();
        
        if(studentMin.time <= 10) {
            System.out.println("버스를 타고 가시는게 가장빠르십니다");
            System.out.println("두 버스중 어느버스를 이용하시겠습니까");
            bus1.showInfo2();
            bus2.showInfo2();
            studentMin.choose = sc.nextInt();
            if(studentMin.choose == 169) {
            bus1.showInfo();
            }else {
                bus2.showInfo1();
            }
            studentMin.takeBus(bus1);
        }//end if
        
        if(studentMin.time > 10) {
            System.out.println("지하철를 타고 가시는게 가장빠르십니다");
            System.out.println("어느 호선의 지하철을 이용하시겠습니까");
            subway1.showInfo2();
            subway2.showInfo2();
            studentMin.choose = sc.nextInt();
            if(studentMin.choose == 1) {
            subway1.showInfo();
            }else {
                subway2.showInfo1();
            }            
            studentMin.takeSubway(subway1);
        }//end if
        studentMin.showInfo();
    }
 
}
 
cs

접근 제어 지시자

public —> 어디에서든 접근 가능 함.

default —> 같은 패키지 내에서 접근 가능

protected ← 상속 배운 이후

private —> 해당 .java 안에서만 접근이 가능하다.

!! 포인트

객체에 상태 값은 행위를 통해서 변경 시키는 것이 객체 지향 코드 방법이다.

get : read-only 성질을 가진다 .

set : 개발자 선택에 의해서 만들 수 있고, 방어적 코드를 작성할 수 있다.

'자바' 카테고리의 다른 글

this가 하는 일  (0) 2023.02.14
객체와 객체간의 상호작용 정보은닉(infomation hiding)  (0) 2023.02.14
객체지향 프로그래밍이란?  (0) 2023.02.14
생성자  (0) 2023.02.14
인스턴스 (instance) 와 힙 메모리  (0) 2023.02.14

객체와 객체간에 관계를 형성하고 상호작용하게 코드를 설계하는것

 

Bus, Subwey

객체와 생성자를 활용하여 만들어보기

 

class 객체코드

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
package ch04;
 
public class Bus {
 
    int busNumber;// 버스 호선
    int passengerCount;// 승객수
    int money;// 수익금
 
    public Bus(int busNumber) {
        this.busNumber = busNumber;
    }
 
    // 기능
    // 달린다
    public void run() {
        System.out.println("버스가 출발합니다.");
    }
 
    // 승차 시키다
    public void take(int count) {
        // this.passengerCount++;
        // this.money += 1_000;
 
        this.passengerCount += count;
        this.money += (1_000 * count);
    }
 
    // 하차 시키다
    public void takeOut(int count) {
        this.passengerCount -= count;
        System.out.println(count +"명의 승객이 내립니다.");
    }
 
    public void showInfo() {
        System.out.println("상태창");
        System.out.println("버스 번호 : " + this.busNumber);
        System.out.println("승객수 : " + this.passengerCount);
        System.out.println("수익금 : " + this.money);
        
    }
}
 
cs
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 ch04;
 
public class Subway {
 
    int lineNumber;
    int passengerCount;
    int money;
    
    public Subway(int lineNumber) {
        this.lineNumber = lineNumber;
    }
    
    public void take(int count) {
        this.passengerCount += count;
        this.money += (1_2500*count);
        System.out.println(count +"명의 승객이 탑니다.");
    }
    
    public void takeOut(int count) {
        this.passengerCount -= count;
        System.out.println(count +"명의 승객이 내립니다.");
    }    
    
    public void showInfo() {
        System.out.println("상태창");
        System.out.println("지하철 호선 번호 : "+this.lineNumber);
        System.out.println("승객수 : "+this.passengerCount);
        System.out.println("수익금 : "+this.money);
    }
}
 
cs

main 코드

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
package ch04;
 
public class MainTest1 {
//코드의 시작점 main
    public static void main(String[] args) {
        Bus bus = new Bus(100);
        bus.take(1);//태우다
        bus.take(1);//태우다
        bus.take(3);//태우다
        
        bus.takeOut(1);
        bus.showInfo();
 
        Subway subway = new Subway(50);
        subway.take(15);
        subway.take(17);
        subway.take(10);
        
        subway.takeOut(9);
        subway.takeOut(2);
        subway.showInfo();
    }//end of main
 
}//end of class
 
cs

내리는 승객과 타는 승객의 수를 계산하기 위하여 (count)매게변수를 사용

 

게임 캐릭터 전사와 마법사

객체와 생성자를 사용하여 만들어보자

전사!

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
package ch04;
 
//전사 클래스 설계하기
public class Warrior {
 
    // 상태
    int lebel;
    int stat;
    int hp;
 
    // 기능
    public Warrior(int lebel) {
        this.lebel = lebel;
        this.hp = this.lebel * 10_000;
    }
 
    public void attack(int power) {
        System.out.println("전사가" + power + "번 공격을 합니다.");
        this.hp -= power * 1000;
 
        System.out.println("전사의 HP가" + power * 1000 + "감소 합니다.");
        System.out.println("전사의 남은HP는" + this.hp + " 입니다.");
 
    }
 
    public void shield(int move) {
        System.out.println("전사가" + move + "번 방어를 합니다.");
        this.hp += move * 500;
 
        System.out.println("전사의 HP가" + move * 500 + "증가 합니다.");
        System.out.println("전사의 남은HP는" + this.hp + " 입니다.");
    }
 
    public void portion() {
        if (this.hp <= 1000000) {
 
            System.out.println("전사의 남은HP가 " + this.hp + "로 1000000 이하입니다 포션을 먹으세요");
        }
    }
 
}
 
cs

마법사!

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 ch04;
 
//마법사 클래스 설계하기
public class Wizard {
 
    int lebel;
    int stat;
    int mp;
 
    public Wizard(int lebel) {
        this.lebel = lebel;
        this.mp = this.lebel * 10_000;
    }
 
    public void sunCool(int power) {
        System.out.println("마법사가" + power + "번 마법을 사용니다.");
        this.mp -= power * 100000;
 
        System.out.println("마법사의 MP가" + power * 10000 + "감소 합니다.");
        System.out.println("마법사의 남은MP는" + this.mp + " 입니다.");
    }
 
    public void evade(int move) {
        System.out.println("마법사가" + move + "번 회피를 합니다.");
        this.mp += move * 1000;
 
        System.out.println("마법사의 mp가" + move * 1000 + "증가 합니다.");
        System.out.println("마법사의 남은mp는" + this.mp + " 입니다.");
    }
 
    public void portion() {
        if (this.mp <= 1000000) {
 
            System.out.println("마법사의 남은mp가 " + this.mp + "로 1000000 이하입니다 포션을 먹으세요");
        }
    }
 
}
 
cs

main 코드

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
package ch04;
 
public class GameTest {
 
    public static void main(String[] args) {
        Warrior warrior = new Warrior(170);
 
        warrior.attack(1000);
        System.out.println("--------------");
        warrior.shield(500);
        System.out.println("--------------");
        warrior.portion();
        System.out.println("=====================================================");
 
        Wizard wizard = new Wizard(430);
 
        wizard.sunCool(35);
        System.out.println("--------------");
        wizard.evade(50);
        System.out.println("--------------");
        wizard.portion();
    }
 
}
 
cs

1.객체를 생성할 때 new 키워드와 함께 사용 - new Student();

2.생성자는 일반 함수처럼 기능을 호출하는 것이 아니고 객체를 생성하기 위해 new 와 함께 호출 됨

3.객체가 생성될 때 변수나 상수를 초기화 하거나 다른 초기화 기능을 수행하는 메서드를 호출 함

4.생성자는 반환 값이 없고, 클래스의 이름과 동일

5.대부분의 생성자는 외부에서 접근 가능하지만, 필요에 의해 private 으로 선언되는 경우도 있음

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 ch02;
 
public class Student {
 
    //생성자 -  constructor
    //객체를 생성 할때 다음과 같은 모양으로 객체를 만들어라고 지시 하는것
    //강제성을 부여하는 거와 같다,
    //생성자는 객체를 생성 할때 반드시 존재 해야한다.!!
    
    String name;
    int number;
    int grade;
    // 생성자 만들어 보기 (사용자 정의 생성자)
    //문법 - 생성자는 리턴타입이 없다 파일 이름과 같다
    //대문자로 시작하고 있다, --> 대소문자 까지
    // 생성자를 선언 하는 문법(설계)
    public Student(String s, int n,int g) {
        name = s;
        number = n;
        grade = g;
    }
    //메게변수가 아무것도 없다 --> 기본생성자
    //사용자 정의 생성자를 만들지 않았다면(개발자가) 자동으로 코드를 넣어준다 ->컴파일러가
    public Student() {
        
    }
    
}
 
cs
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
package ch02;
 
public class MainTest1 {
//메인함수
    public static void main(String[] args) {
        //기본생성자
        Student studentHong = new Student(); // 컴파일러가 알아서 넣어줌
        studentHong.grade = 1;
        studentHong.name = "홍길동";
        studentHong.number = 1234;
        //객체를 생성할때 반드시 하나 이상에 생성자가 있어야함
        
        Student studentKim = new Student("홍길동"12341);
        System.out.println(studentKim.name);
        System.out.println(studentKim.grade);
        System.out.println(studentKim.number);
        //객체를 생성 할때 강제성을 부여하는것
        
        //사용자 정의 생성자를 하나라도 만들었다면 컴파일러는 기본생성자를 만들어 주지 않는다.
        
        //생성자 --> 2개 (생성자는 여러개 만들수 있다)
        //생성자 오버 로딩 (생성자를 여러개 만들어 주는 기법)
    }//end of main
 
}//end of class
 
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package ch02;
 
public class Student2 {
 
    String name;
    int grade;
 
    //this는 자기자신이다.
    public Student2(String name, int grade) {
        this.name = name;
        this.grade = grade;
    }
 
}
 
cs

!@!!! 중요 같은 명을 사용할땐 자기 자신의 이름앞에(this)

 

생성자를 사용한 예제 (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
32
33
34
35
36
37
38
package ch02;
 
public class UserInfo {
 
    String userId;
    String userName;
    String phone;
    
    //사용자 정의 생성자를 만들어주세요 매개변수 3개 한번에 사용
    public UserInfo(String userId,String userName,String phone) {
        this.userId = userId;
        this.userName = userName;
        this.phone = phone;
    }
    
    //사용자 정의 생성자 만들기 userId : userName;
    public UserInfo(String userId,String userName) {
        this.userId = userId;
        this.userName = userName;
    }
    //사용자 정의 생성자 만들기 userId;
    public UserInfo(String userId) {
        this.userId = userId;
    }
    //기본생성자 만들기
    public UserInfo() {
        
    }
    
    public void Info5() {
        System.out.println("=========상태창=========");
        System.out.println("유저의 ID값은 : " + userId);
        System.out.println("유저의 이름은 : " + userName);
        System.out.println("유저의 주소은 : " + phone);
        System.out.println("=======================");
    }
}
 
cs
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 ch02;
 
public class UserInfoMainTest {
 
    public static void main(String[] args) {
        // 기본 생성자는 사용자 정의 생성자가 하나라도 있으면 만들어 주지않는다
        UserInfo userInfo1 = new UserInfo();
        userInfo1.userId = "Flower";
        userInfo1.userName = "김민우";
        userInfo1.phone = "010-3837-0000";
        System.out.println(userInfo1.userId);
        System.out.println(userInfo1.userName);
        System.out.println(userInfo1.phone);
        
        
        UserInfo userInfo2 = new UserInfo("Flower");
        System.out.println(userInfo2.userId);
        
        UserInfo userInfo3 = new UserInfo("Flower""김민우");
        System.out.println(userInfo3.userId);
        System.out.println(userInfo3.userName);
            
        UserInfo userInfo4 = new UserInfo("Flower""김민우","010-3837-0000");
        System.out.println(userInfo4.userId);
        System.out.println(userInfo4.userName);
        System.out.println(userInfo4.phone);
        
        userInfo1.Info5();
        
    }//end of main
 
}//end of class
 
cs

참조 자료형 활용

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
package ch03;
 
public class Student {
 
    int studentId;
    int grade;
    //참조타입
    String name;
    //참조타입
    Subject Korea;
    Subject math;
    
//생성자
    public Student(int studentId, int grade, String name) {
        this.studentId = studentId;
        this.grade = grade;
        this.name = name;
        
        this.Korea = new Subject();
        this.math = new Subject();
    }
    
    //메서드
    public void showInfo() {
        System.out.println("**상태창**");
        System.out.println(this.name +" : 입니다");
        System.out.println(this.grade +" : 학년 입니다");
        System.out.println(this.studentId +" : 번 입니다");
        System.out.println(this.Korea.subjectName+"에 점수는"+this.Korea.score);
        //System.out.println(this.math.subjectName+"에 점수는"+this.math.score);
    }
    public void showInfo2() {
        System.out.println("**상태창**");
        System.out.println(this.name +" : 입니다");
        System.out.println(this.grade +" : 학년 입니다");
        System.out.println(this.studentId +" : 번 입니다");
        System.out.println(this.Korea.subjectName+"에 점수는"+this.Korea.score);
        System.out.println(this.math.subjectName+"에 점수는"+this.math.score);
    }
 
}
 
cs
1
2
3
4
5
6
7
8
9
package ch03;
 
public class Subject {
    
    String subjectName;
    int score;
    int subjectId;
}
 
cs
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 ch03;
 
//객체지향 프로그래밍란
//객체와 객채간에 관계를 형성하고 상호 작용하게 코드를 설계해 나가는것
public class MainTest1 {
 
    public static void main(String[] args) {
        //1번 3,홍길동
        //2번 3,이순신
        Student studentHong = new Student(1,3,"홍길동");
        Student studentLee = new Student(2,3,"이순신");
        
        //변수로 접근해서 데이터 추가
        //컴파일 시점에 오류를 확인할수 없는 상태 였다.(실행 시점에 오류가 확인
        //메모리에 올라가지 않은상태 -- 
        //해결 방법 -1번 내부에서 초기화 하는 방법 -2번 외부에서 초기화하기
        studentHong.Korea.subjectName = "국어";
        studentHong.Korea.score = 90;
        studentHong.showInfo();
        //System.out.println(studentHong.Korea);
        
        //이순에 과목 국어 수학 이름 데이터를 입력
        //이순에 과목 점수 국어 100, 수학 5점 입력
        //출력하는 코드를 작성
        
        
        studentLee.Korea.subjectName = "국어";
        studentLee.Korea.score = 100;
        
        studentLee.math.subjectName = "수학";
        studentLee.math.score = 5;
        studentLee.showInfo2();
        
            
    }
 
}
 
cs

참조 변수를 사용하였기 때문에 불러오는 과정에서 바로 사용하지 못하여 클래스 설계도 파일에서 new로 호출후 main 파일에 적용 가능함

 

+ Recent posts