항해99 온보딩 스터디[Java 언어 기초] 5일차

Hohomi·2023년 3월 10일
0
post-thumbnail

스터디 5일차 : 객체지향 프로그래밍 1 (Object-oriented Programming)


💡 클래스와 객체, 인스턴스(class, object, instance)

  • 클래스 : 객체를 정의해놓은 것. 객체의 설계도 또는 틀. 객체를 생성하는 데 사용된다. 붕어빵 기계(틀)
  • 객체 : 실제로 존재하는 것. 사물 또는 개념. 클래스에 정의된 내용대로 메모리에 생성된 것. 붕어빵
    - 멤버 : 객체가 가지고 있는 속성과 기능. 멤버변수, 메서드 등
  • 인스턴스 : 클래스로부터 만들어진 객체

💡 객체의 생성과 사용

Tv t;		// 클래스의 객체를 참조하기 위한 참조변수를 선언
t= new Tv(); // 클래스의 객체를 생성 후, 객체의 주소를 참조변수에 저장
//예제
public class Ex6_1 {
    public static void main(String[] args) {
        Tv t; // Tv인스턴스를 참조하기 위한 변수 t를 선언
        t = new Tv(); // Tv인스턴스를 생성해서 참조변수 t에 저장한다.
        t.channel = 7; // Tv인스턴스의 멤버변수 channel의 값을 7로 한다.
        t.channelDown(); // Tv인스턴스의 메서드 channelDown()을 호출한다.
        System.out.println("현재 채널은 " + t.channel + " 입니다.");
    }
}

class Tv {
    // Tv의 속성(멤버변수)
    String color; // 색상
    boolean power; // 전원상태(on/off)
    int channel; // 채널

    // Tv의 기능(메서드)
    void power() { power = !power; } // Tv를 켜거나 끄는 기능을 하는 메서드
    void channelUp() { ++channel; } // Tv의 채널을 높이는 기능을 하는 메서드
    void channelDown() { --channel; } // Tv의 채널을 낮추는 기능을 하는 메서드
}
//예제2
public class Ex6_2 {
    public static void main(String[] args) {
        Tv t1 = new Tv();
        Tv t2 = new Tv();
        System.out.println("t1의 channel값은 " + t1.channel +"입니다.");
        System.out.println("t2의 channel값은 " + t2.channel +"입니다.");

        t1.channel = 7;
        System.out.println("t1의 channel값을 7로 변경하였습니다.");

        System.out.println("t1의 channel값은" + t1.channel + "입니다.");
        System.out.println("t2의 channel값은" + t2.channel + "입니다.");
    }
}
  • 클래스는 주로 이렇게 이루어져 있다.(변수 / 메서드 / 생성자)

💡 클래스 변수와 인스턴스 변수

//예제
public class Ex6_3 {
    public static void main(String[] args) {
        Card c1 = new Card();
        c1.kind = "Heart";
        c1.number = 7;

        Card c2 = new Card();
        c2.kind = "Spade";
        c2.number = 4;
        
        Card.width = 50;
        Card.height = 80;
    }
}

class Card {
    String kind;        //인스턴스 변수
    int number;
    static int width = 100;     //클래스 변수
    static int height = 250;
}

💡 메서드(method)

  • 특정 작업을 수행하는 문장들을 하나로 묶은 것
  • 수학의 '함수'와 유사!
  • 어떤 값을 입력하면 그 값으로 작업을 수행해서 결과를 반환한다.
  • 입력값, 출력값이 없는 경우도 있다.
  • 메서드를 선언할 때 메서드 앞에 반환값의 타입을 적어야 하는데, 반환값이 없는 경우 반환타입으로 'void'를 적는다.
  • return문은 단 하나의 값만 반환할 수 있다.
  • 반환값의 타입은 메서드의 반환타입과 일치하거나 자동 형변환이 가능한 것이어야 한다.
👇 메서드의 형태 👇
반환타입 메서드(파라미터) { 인풋 };

* 인풋 : 없는 경우도 있음
* 파라미터(parameter) : 매개변수

ex)
int add(int x, int y) {
return result;			// 결과를 반환
}
⭐️ 반환값이 없는 경우 : ex) 구구단 전체 출력

void print99danAll() {
	for(int i=1; i<=9; i++) {
	    for(int j=2; j<=9; j++) {
        }
    }
}
⭐️ 메서드의 실행 흐름 예제
public class Ex6_4 {
    public static void main(String[] args) {
        MyMath mm = new MyMath();
        long result1 = mm.add(5L, 3L);
        long result2 = mm.subtract(5L, 3L);
        long result3 = mm.multiply(5L, 3L);
        double result4 = mm.divide(5L, 3L);
    }
}

class MyMath {
    long add(long a, long b) {
        long result = a + b;
        return result;
    }
    long subtract(long a, long b) { return a - b; }
    long multiply(long a, long b) { return a * b; }
    double divide(double a, double b) { return a / b; }
}



📖 『JAVA의 정석 기초편』 연습문제 풀이!

Chater 6

6-1.

다음과 같은 멤버변수를 갖는 Student클래스를 정의하시오.

타입변수명설명
Stringname학생이름
intban
intno번호
intkor국어점수
inteng영어점수
intmath수학점수
class Student {
    String name;
    int ban;
    int no;
    int kor;
    int eng;
    int math;
}

6-2.

다음과 같은 실행결과를 얻도록 Student클래스에 생성자와 info()를 추가하시오.

  • 결과 : 홍길동, 1, 1, 100, 60, 76, 236, 78.7
public class Quiz6_2 {
    public static void main(String[] args) {
       Student s = new Student("홍길동", 1, 1, 100, 60, 76);

       String str = s.info();
       System.out.println(str);
    }
}

class Student {
    String name;
    int ban;
    int num;
    int kor;
    int eng;
    int math;

    Student(String name, int ban, int num, int kor, int eng, int math) {
        this.name = name;
        this.ban = ban;
        this.num = num;
        this.kor = kor;
        this.eng = eng;
        this.math = math;
    }
    int total() {
        return kor + eng + math;
    }
    float average() {
        return (int)(total() / 3f * 10 + 0.5f) / 10f;
    }

    String info() {
        return name+","+ban+","+num+","+kor+","+eng+","+math+","+total()+","+average();
    }
}



📍 참고 자료

참고 도서 : 『JAVA의 정석 기초편』, 남궁 성, 도우출판

profile
게발로 개발하기

0개의 댓글