Title
💡 객체지향 프로그래밍, 클래스와 인스턴스 개념 알아보고 실습하기ex)
학생, 회원, 주문, 생산, 배송을 객체가 될 수 있다.
ex)
속성 = 사람의 나이, 이름
동작 = 달리다, 잠자다, 공부하다
객체의 속성은 필드(field),
객체의 동작은 메소드(method)라고 불린다.
다음의 그림을 살펴보자
여기서 객체란 “본문, 댓글, 글목록”으로 구분할 수 있으며
오른쪽의 그림처럼
자료출처: https://www.opentutorials.org/course/1223/5399, https://computer-science-student.tistory.com/288
//클래스
class Calculator{
//변수 선언 (속성)
int left,right;
//메소드 (행위)
//setOprands - 초기화 (left 값, right 값)
public void setOprands(int left, int right) {
this.left = left;
this.right = right;
}
//메소드(행위)
//sum - 덧셈
public void sum(){
System.out.println(this.left+this.right);
}
//메소드(행위)
//avg - 평균
public void avg(){
System.out.println((this.left+this.right)/2);
}
}
//클래스
public class CalculatorDemo4 {
public static void main(String[] args) {
//인스턴스 생성
Calculator c1 = new Calculator();
//left = 10. right = 20으로 설정
c1.setOprands(10, 20);
//덧셈
c1.sum(); //10 + 20 = 30
// 평균
c1.avg(); // 10 +20 /2 = 15
//인스턴스 생성
Calculator c2 = new Calculator();
//left = 20, right = 40
c2.setOprands(20, 40);
//덧셈
c2.sum(); //20 + 40 = 60
//평균
c2.avg(); // 20 + 40 / 2 = 30
}
}
출력값
30
15
60
30
자료 출처: https://whatisthenext.tistory.com/36, https://www.opentutorials.org/course/1223/5400