Java

[2024-2 Java 스터디] #3주차 "클래스, 메서드"

디지몬진화 2024. 10. 30. 22:45

05. 객체 지향 프로그래밍

 

05-1 객체 지향 프로그래밍이란?

 

- 자바를 계산기에 비유하자면 위와 같이 계산기를 두개 만들필요 없이 객체를 사용하여 아래와 같이 간단히 해결 가능

- Calculator 클래스로 만든 별개의 계산기 cal1, cal2 가 각각 역할을 수행

- 계산기 cal1, cal2 (이것을 객체라 함) 의 결괏값은 독립적인 값을 유지

class Calculator1 {
    static int result = 0;

    static int add(int num) {
        result += num;
        return result;
    }
}

class Calculator2 {
    static int result = 0;

    static int add(int num) {
        result += num;
        return result;
    }
}


public class Sample {
    public static void main(String[] args) {
        System.out.println(Calculator1.add(3));
        System.out.println(Calculator1.add(4));

        System.out.println(Calculator2.add(3));
        System.out.println(Calculator2.add(7));
    }
}
class Calculator {
    int result = 0;

    int add(int num) {
        result += num;
        return result;
    }
}


public class Sample {
    public static void main(String[] args) {
        Calculator cal1 = new Calculator();  // 계산기1 객체를 생성한다.
        Calculator cal2 = new Calculator();  // 계산기2 객체를 생성한다.

        System.out.println(cal1.add(3));
        System.out.println(cal1.add(4));

        System.out.println(cal2.add(3));
        System.out.println(cal2.add(7));
    }
}

 

 

05-2 클래스

 

1. 클래스와 객체

- 클래스는 객체를 만드는 기능을 가짐

class Animal {
}

public class Sample {
    public static void main(String[] args) {
        Animal cat = new Animal();  //Animal 클래스인 cat 객체 만들기
    }
}

▲ Animal 클래스는 선언만 있고 내용은 없지만 Animal cat = new Animal() 과 같이 객체를 만드는 기능을 가지고 있다.

 

 

1.1 객체 변수 생성

 

- 객체 : 클래스에 의해 생성되는 것

- 객체 변수 : 클래스에 선언된 변수

class Animal {
    String name;
}

public class Sample {
    public static void main(String[] args) {
        Animal cat = new Animal();
    }
}//객체는 cat이고 객체 변수는 name이다.

 

- 객체 변수는 도트 연산자(.)를 이용해 접근 가능

cat.name  // 객체.객체변수를 통해 접근 가능

 

2. 메서드란?

- 메서드 : 클래스 내에 구현된 함수

class Animal {
    String name;

    public void setName(String name) { //Animal 클래스 안에 다음 메서드 추가
        this.name = name; //this.name 은 Animal클래스 최상부에 호출한 String name;이다
    }
}
cat.setName("boby");  // 메서드 호출

 

- setName 메서드 형태

  • 입력 : String name
  • 출력 : void ('리턴값 없음'을 의미)

 

3. 객체 변수는 공유되지 않는다

- 객체 변수의 값이 독립적으로 유지

class Animal {
    String name;

    public void setName(String name) {
        this.name = name;
    }
}

public class Sample {
    public static void main(String[] args) {
        Animal cat = new Animal();
        cat.setName("boby");  // 메서드 호출

        Animal dog = new Animal();
        dog.setName("happy");

        System.out.println(cat.name);
        System.out.println(dog.name);
    }
}

cat.name = "boby" 이후에 dog.name = "happy"가 수행되더라도 cat.name은 happy로 값이 바뀌지 않음

 

 

05-3 메서드 더 살펴보기

- 입력값을 가지고 어떤 일을 수행한 후 결과값을 내어놓는 것이 메서드의 일

 

 

1. 메서드를 사용하는 이유

- 여러번 반복해서 사용 가능 -> 또다시 사용할 만한 가치가 있는 부분이라는 것을 의미

 

  • 메서드의 정의
int sum(int a, int b) {
    return a+b;
}
//“sum 메서드는 입력값으로 두개의 값(int 자료형 a, int 자료형 b)을 받으며 
//리턴값은 두 개의 입력값을 더한 값(int 자료형)이다.”

 

2. 매개 변수와 인수

- 매개 변수 : 메서드에 전달된 입력값을 저장하는 변수

- 인수 : 메서드를 호출할 때 전달하는 입력값

public class Sample {
    int sum(int a, int b) {  // a, b 는 매개변수
        return a+b;
    }

    public static void main(String[] args) {
        Sample sample = new Sample();
        int c = sample.sum(3, 4);  // 3, 4는 인수

        System.out.println(c);
    }
}

 

3. 입력값과 리턴값 모두 없는 메서드의 사용법

public class Sample {
    void say() {
        System.out.println("Hi");
    }

    public static void main(String[] args) {
        Sample sample = new Sample();
        sample.say();
    }
}

 

 

4. return의 또 다른 쓰임

- return을 단독으로 사용하여 메서드 즉시 빠져나옴

public class Sample {
    void sayNick(String nick) {
        if ("바보".equals(nick)) {
            return;
        }
        System.out.println("나의 별명은 "+nick+" 입니다.");
    }

    public static void main(String[] args) {
        Sample sample = new Sample();
        sample.sayNick("야호");
        sample.sayNick("바보");  // 출력되지 않는다.
    }
}

 

5. 메서드 내에서 선언된 변수의 효력 범위

- 메서드에서 사용한 매개변수는 매서드 안에서만 쓰이는 변수이므로 매서드 밖 변수 a와는 다름

public class Sample {
    void varTest(int a) {
        a++;
    }

    public static void main(String[] args) {
        int a = 1;
        Sample sample = new Sample();
        sample.varTest(a);
        System.out.println(a); //a는 2가 아닌 1이 출력
    }
}

※ varTest 메서드에 return문을 사용하여 main에서 a에 대입을 해주어야 1 증가되는것이 적용

     혹은 sample.a++ 를 사용하여 Sample클래스에 객체 변수 a를 설정 후 증가해주어야 함

     혹은 this.a 를 사용하여 객체변수 a의 값을 증가해주어야 함

 

 

05-4 값에 의한 호출과 객체에 의한 호출

- 메서드에 객체를 전달할 경우 메서드에서 객체 변수의 값을 변경할 수 있음

class Updater {
    void update(Counter count) {
        counter.count++;
    }
}

class Counter {
    int count = 0;  // 객체변수
}

public class Sample {
    public static void main(String[] args) {
        Counter myCounter = new Counter();
        System.out.println("before update:"+myCounter.count);
        Updater myUpdater = new Updater();
        myUpdater.update(myCounter.count);
        System.out.println("after update:"+myCounter.count);
    }
}
//before update:0
//after update:1