Java 문법 : 클래스, 인스턴스, 메소드

김선미·2022년 6월 4일
0

클래스

  • 일정한 공통 속성을 한 곳에 정의해놓은 것을 의미한다.
  • 클래스 내부의 각 속성을 멤버 변수라고 한다.
class Phone {
    String model;
    String color;
    int price;
}

# phone 이라는 클래스 안에 멤버 변수인 model, color, 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 = "iPhoneX";
        iphone.color = "Black";
        iphone.price = 200;


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

# 클래스를 통해 만들어진 galaxy, iphone가 인스턴스(객체)이다.

메소드

  • 특정 작업을 하는 코드를 하나로 모아 놓은 것
  • 일정한 작업 단위, 중복된 코드가 있을 때 사용한다.
  • 프로그램의 구조화와 재사용성에 도움이 된다.
  • 되도록 동사 형태로 기재하고, 케멀 케이스 형태로 기재한다.
# 메소드 생성(add, subtract)
# 함수 내의 파라미터 값은 함수 내에서만 통용되며 함수 바깥에서는 통용되지 않는다.

class Caculation {
    int add(int x, int y){
        return x + y;
    }
    int subtract(int x, int y){
        return x - y;
    }
}

# 인스턴스(caculation) 메소드(add, subtract) 사용

public class Main {
    public static void main(String[] args) {
        Caculation caculation = new Caculation();
        int addresult = caculation.add(1,2);
        int subtractresult = caculation.subtract(5,3);
        System.out.println(addresult);
        System.out.println(subtractresult);
    }
}
profile
백엔드 개발 공부

0개의 댓글