Java_문법뽀개기 02

5w31892p·2022년 11월 14일
0

Java

목록 보기
3/17

📜 Java

:: ✍ 객체지향언어

:: Class

  • 붕어빵 틀
  • 어떤 속성을 갖는지, 어떤 모양을 갖는지 정해져 있음
  • 클래스 내부 정보 == 멤버변수

:: Instance

  • 붕어빵 틀을 통해 만들어진 붕어빵!
  • 즉, 클래스로부터 만들어진 객체
  • 붕어빵을 한입 베어먹어도 그대로 붕어빵인 것처럼
  • 인스턴스는 한번 생성되고나면 그 자체의 상태로 변화됨

인스턴스가 멤버 변수에 접근할 때의 형식

  • " 생성된 인스턴스 . 멤버변수 의 형식으로 사용
class Phone {
    String model;
    String color;
    int price;
}

public class Main {
    public static void main(String[] args) {
        Phone galaxy = new Phone(); // 인스턴스 생성
        galaxy.model = "Galaxy10"; // 인스턴스.멤버변수
        galaxy.color = "Black"; // 인스턴스.멤버변수
        galaxy.price = 100; // 인스턴스.멤버변수

        Phone iphone = new Phone();
        iphone.model = "iphone12mini";
        iphone.color = "Black";
        iphone.price = 200;

        System.out.println("철수는 이번에 " + galaxy.model + " " + galaxy.color + " 색상을 " + galaxy.price + "만원에 샀다.");
        System.out.println("영희는 이번에 " + iphone.model + " " + iphone.color + " 색상을 " + iphone.price + "만원에 샀다.");
    }
}

:: Method

  • 작업 수행하는 코드를 하나로 묶어 놓은 것
  • 일정한 작업의 단위, 중복된 코드, 프로그램의 재사용성과 구조화를 위해 method를 선언하여 사용
  • 즉, Method가 필요한 이유
    • 재사용성 : 이후 반복적으로 재사용이 가능 | 다른 프로그램에서도 사용 가능
    • 중복된 코드 제거 : 메소드를 활용하면 중복된 부분을 없애므로 효율적인 코드가 됨
    • 프로그램의 구조화 :
  • Mothod 선언시 암묵적 룰
    • 동사로 시작
    • 카멜케이스
public class Main {
    public static void main(String[] args) {
        int[] heights = new int[]{10, 20, 30, 40, 50};

        initHeight(heights); // 1. 키에 대한 초기화
        sortHeight(heights); // 2. 키를 오름차순으로 정렬
        printHeight(heights); // 3. 정렬된 키를 출력
    }

    int add(int x, int y) {
        // 괄호 안을 parameter 라고 함
        //파라미터는 내가 원하는 만큼 선언해서 쓸 수 있음
        // (타입 변수이름, 타입 변수이름) 이렇게 선언
        return x + y;
    }

    int minus(int x, int y) { // 위 x,y 와는 상관없음
        return x - y;
    }
}

키를 초기화하는 함수가 없다면?

배열에 초기화 하는 로직을 적어줘야함

int[] heights = new int[]{10, 20, 30, 40, 50};

정렬하는 함수가 없다면?

코드를 쭉 적어줘야함

heights[0] = 50
heights[1] = 40

메소드의 형식

  • 반환타입 메소드이름 (타입 변수명,타입 변수명, ...){ 수행되어야 할 코드 }
함수 결과값 전달되는 type 함수명 (type parameter변수명, type parameter변수명);
int addResult = calculation.add(100, 90);

// 함수 결과값 전달되는 type == int
// 함수명 == add
// type == int
// parameter변수명 == x와 y

// parameter는 내가 원하는 만큼 선언해서 쓸 수 있음 

메소드는 return을 통해 수행 결과 반환

  • return 다음은 실제 결과로 넘겨준 값이 어떤 것인지 쓰면 됨
    • 특정값 return도 가능
  • 해당 parameter는 해당되는 함수 안에서만 존재
class Calculation {
    int add(int x, int y) {
        int result = x + y;
        return result;
    }// 두 값을 더한 결과

    int subtract(int x, int y) {
        int result = x - y;
        return result;
    }// 두 값을 뺀 결과
}

public class Main {
    public static void main(String[] args) {
        Calculation calculation = new Calculation(); //  인스턴스를 만들어 주는 것
        int addResult = calculation.add(100, 90);
        int subResult = calculation.subtract(90, 70);

        System.out.println("두 개를 더한 값은 " + addResult); // 190
        System.out.println("두 개를 뺀 값은 " + subResult); // 20
    }
}

선언해놓은 함수는 (ex. calculation) 언제든지 더하든 빼든 다시 하고 싶을 때 반복해서 사용할 수 있음

:: 생성자 (constructor)

  • 인스턴스가 생성될 때 사용되는 인스턴스 초기화 메소드
  • new로 인스턴스 새로 생성될 때 자동 호출
  • 생성자 조건
    • 생성자 이름은 클래스의 이름과 같아야 함
    • 리턴 값 없음
  • 모든 클래스에는 반드시 하나 이상의 생성자 있어야 함
    • 만약 생성자가 1개도 작성되어 있지 않으면 java compiler가 기본 생성자를 추가함
    • 그래서 생성자 만들지 않고 new 사용하여 인스턴스 만들 수 있었던 것
  • this는 생성된 객체 자신
  • 생성자의 매개변수의 값을 객체에 해당하는 데이터에 넣어줌

생성자 만드는 단축키

  • Alt + ins (mac : command + N)
class Phone {
    String model;
    String color;
    int price;

    public Phone(String model, String color, int price) {
        this.model = model;
        this.color = color;
        this.price = price;
    }
}

public class Main {
    public static void main(String[] args) {
        Phone galaxy = new Phone("Galaxy10", "Black", 100);

        Phone iphone =new Phone("iPhoneX", "Black", 200);

        System.out.println("철수는 이번에 " + galaxy.model + galaxy.color + " + 색상을 " + galaxy.price + "만원에 샀다.");
        System.out.println("영희는 이번에 " + iphone.model + iphone.color + " + 색상을 " + iphone.price + "만원에 샀다.");
    }
}
  • class phone 안의 멤버변수와 생성자 phone 안에 parameter는 다름

  • 멤버변수와 constructor안의 parameter 구분하는 방법
    • constructor안에 this. model = model 이 있다고 가정한다면
    • this. 다음에 있는 model은 멤버변수이고,
    • parameter 값으로 받은 model은 constructor에 있는 model
  • 즉, this. model = model 은
    • 객체에 있는 model이라는 변수에 parameter로 받은 model을 할당할 것이라는 의미

  • 생성자 생성 후 Main class 안에 있는 new Phone() 괄호가 비어 있으면 error
    • parameter 받는 constructor(생성자)가 있는데 아무것도 안넣어줬으니 error라는 뜻

생성자를 사용하지 않으면 긴 코드가 생성자를 사용하게 되면 한줄로 끝남

인스턴스 변수의 기본값

  • 생성자로 아무값도 안넣어주면 인스턴스는 멤버변수의 기본값 갖게 됨
class DefaultValueTest {
    byte byteDefaultValue;
    int intDefaultValue;
    short shortDefaultValue;
    long longDefaultValue;
    float floatDefaultValue;
    double doubleDefaultValue;
    boolean booleanDefaultValue;
    String referenceDefaultValue;
}

public class Main {
    public static void main(String[] args) {
        DefaultValueTest defaultValueTest = new DefaultValueTest();
        System.out.println("byte default: " + defaultValueTest.byteDefaultValue);
        System.out.println("short default: " + defaultValueTest.shortDefaultValue);
        System.out.println("int default: " + defaultValueTest.intDefaultValue);
        System.out.println("long default: " + defaultValueTest.longDefaultValue);
        System.out.println("float default: " + defaultValueTest.floatDefaultValue);
        System.out.println("double default: " + defaultValueTest.doubleDefaultValue);
        System.out.println("boolean default: " + defaultValueTest.booleanDefaultValue);
        System.out.println("reference default: " + defaultValueTest.referenceDefaultValue);
    }
}

// byte default: 0   ->   1byte 를 구성하는 8개의 bit가 모두 0이라는 뜻.
// short default: 0
// int default: 0
// long default: 0
// float default: 0.0
// double default: 0.0
// reference default: null

:: 상속 (inheritance)

  • 오직 하나의 클래스만 상속 받을 수 있음
  • 기존 클래스의 재사용 방식 중 하나
  • 특징
    • 부모클래스에서 정의된 필드, 메소드 물려받음
    • 새로운 필드, 메소드 추가 가능
    • 부모 클래스에서 물려받은 메소드 수정 가능 (overriding)
  • 형식
    • 상속은 extends를 이용하여 사용
  • 부모 클래스 == Animal
  • 자식 클래스 == Dog, Cat
class Animal{}
class Dog extends Animal{}
class Cat extends Animal{}

  • 선언부에 부모 타입 가능
class Animal {
    String name;

    public void cry() {
        System.out.println(name + " is crying.");
    }
}

class Dog extends Animal {

    Dog(String name) {
        this.name = name;
    }

    public void swim() {
        System.out.println(name + " is swimming!");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog("코코"); // constructor 생성
        dog.cry();
        dog.swim();

        Animal dog2 = new Dog("미미"); // 선언부에 부모타입 가능
        dog2.cry();
//        dog2.swim(); // compile error : swim은 자식타입에 있는 함수이기 때문
    }
}

Animal type의 dog2라는 변수인데 얘의 구현체, 실제는 위에 dog으로 생성한 객체라는 의미

Animal dog2 = new Dog("미미");

Animal에 있는 변수만 할당 받을 수 있음

  • 자식타입에 있는 함수는 받을 수 없음
dog2.swim();

:: super()

  • 상속받은 필드나 메소드를 자식 클래스에서 참조하여 사용하고 싶을 때 사용

:: overloading

  • 한 클래스 내 동일한 이름의 메소드 여러 개 정의
  • 메소드 이름만 같다고 해서 무조건 오버로딩 X
  • 오버로딩 조건
    • 메소드 이름 동일
    • 매개변수 개수 또는 타입 달라야함 (개수, 타입 둘 중 하나만 달라도 OK)
1. 리턴타입만 다르고 자료형과 개수가 같은 것 오버로딩 X
public class Main {
    public static void main(String[] args) {
    }

    int add(int x, int y, int z) {
        return x + y + z;
    }
    long add(int a, int b, int c) {
        return a + b + c;
    }
} // 타입, 개수 동일


2. 이름 같고,  매개변수의 개수가 다름 오버로딩 O
public class Main {
    public static void main(String[] args) {
    }

    int add(int x, int y, int z) {
        return x + y + z;
    }
    int add(int a, int b) {
        return a + b;
    }
}

3. 개수는 같은데 타입이 다른 경우 오버로딩 O
public class Main {
    public static void main(String[] args) {
    }

    int add(int x, int y, int z) {
        return x + y + z;
    }
    long add(int a, int b, long c) {
        return a + b + c;
    }
}

:: overloading

  • 상속받은 메소드를 자식이 정의 하는 것 == 덮어버리는 것
  • 부모에 있던 원래 함수의 내용은 없는 없는 셈 치는 것
  • 자식이 override 한 것만 수행
  • 오버라이딩 조건
    • 메소드 이름 동일
    • 매개변수 매개변수와 반환타입 같아야함 (매개변수, 반환타입 모두 같아야 OK)
class Animal {
    String name;
    String color;

    public Animal(String name) {
        this.name = name;
    }

    public void cry() {
        System.out.println(name + " is crying");
    }
}

class Dog extends Animal {

    public Dog(String name) {
        super(name);
    }

@Override
    public void cry() {
        System.out.println(name + " is barking!");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal dog = new Dog("코코");
        dog.cry();
    }
}

// 코코 is barking!

overloading

기존에 없는 새로운 메소드 정의하는데 같은 이름을 가지는 함수를 정의

overriding

부모에 있는 똑 같은 함수를 자식이 구현해서 부모에 있는 함수를 없는체 하는 것
즉, 상속받은 메소드 내용 변경

0개의 댓글