
정의: 주체가 아닌 것, 주체가 활용하는 것 → 우리 주변에 있는 모든 것
→ 현실 세계를 반영하는 프로그래밍
객체지향 프로그래밍의 장점
신뢰성 높은 프로그래밍이 가능하다.
추가/수정/삭제가 용이하다
재사용성이 높다
클래스와 객체
현실의 객체가 갖는 속성과 기능은 추상화(abstraction)되어 클래스에 정의된다.
클래스는 구체화 되어 프로그램의 객체(instance,object)가 된다.
설계도는 하나의 Type이 되고 설계도를 통해 나온 제품을 객체라고 부르며 주체가 사용한다.
클래스: 객제를 정의해 놓은 것, 객체의 틀. 직접 사용x 객체를 만들기 위한 틀만 제공
객체: 클래스를 데이터 타입으로 메모리에 생성된 것
public class Person {
String name;
int age;
boolean isHungry;
void eat() {
System.out.println("냠냠");
isHungry = false;
}
void work() {
System.out.printf("%n");
System.out.println("열심히");
isHungry = true;
}
}
public class PersonTest {
public static void main(String[] args) {
Person p = new Person();
p.name = "홍길동";
p.isHungry = true;
p.eat();
System.out.println(p.name+": "+p.isHungry+" "+p.age);
Person p2 = new Person();
p2.name = "장길산";
p2.work();
System.out.println(p2.name+": "+p2.isHungry+" "+p2.age);
}
}
객체 생성과 메모리(JVM의 메모리 구조)

타입에 따른 분류 vs 선언 위치에 따른 분류
타입에 따른 분류 → Primitive Type vs Reference Type
선언 위치에 따른 분류 → 멤버변수 vs 지역변수

→ 객체를 만들 때마다 객체 별로 생성 → 객체마다 고유한 상태유지
public class Person{
//모든 객체들에 대해서 같은 멤버변수 값을 가진다
static String scientificName = "Homo Sapiens";
String name;
}
System.out.println(Person.org);
-> 출력값: Homo Sapiens
Person p = new Person();
p.scientificName = "객체를 통한 변경";
//static에 부합하는 내용은 아님
Person.scientificName = "클래스를 통한 변경";
//클래스를 통해 변경하는 것을 지향
void call(String to){ //파라미터 변수
String beep = "띠"; //로컬 변수
for(int i = 0; i < 3; i++){ //로컬변수
System.out.println(beep);
}
}
메서드란?
→ 현실의 객체가 하는 동작을 프로그래밍으로 어떤 작업을 수행하는 명령문의 집합
→ 반복적으로 사용되는 코드의 중복 방지
→ 코드 양을 줄일 수 있고 유지 보수가 용이하다.
public class Person {
String name;
int age;
boolean isHungry;
static String org = "SSAFY";
//사람 정보에 대한 메서드
void printInfo() {
System.out.println(this.name+": "+this.isHungry+" "+this.age);
}
}
public class PersonTest {
public static void main(String[] args) {
System.out.println(Person.org);
Person p = new Person();
p.name = "홍길동";
p.isHungry = true;
p.eat();
//System.out.println(p.name+": "+p.isHungry+" "+p.age);
p.printInfo();
Person p2 = new Person();
p2.name = "장길산";
p2.work();
//System.out.println(p2.name+": "+p2.isHungry+" "+p2.age);
p2.printInfo();
}
}
public static void main(String[] args){
VariableTest vt = new VariableTest();
vt.variableArgs(1,2,3);
vt.variableArgs(1,2,3,4);
vt.variableArgs(1,2);
}
public void variableArgs(int... params){
int sum = 0;
for(int i: params){
sum += i;
}
}
메서드 호출 → 메서드를 호출할 때는 메서드의 선언부에 맞춰 호출해야 함
메서드 접근 → 멤버 변수와 마찬가지로 static 또는 non static 상태를 구분해서 호출

가장 중요한 것은 호출하려는 멤버가 메모리에 있는가? 를 생각해야한다.
if : 메모리에 있으면 호출가능
else: 메모리에 없으면 호출 불가(먼저 메모리에 로딩 후 사용해야 함 )
static memeber는 언제나 메모리에 있어서 클래스 로딩 시 자동 등록
but instance memeber는 객체 생성 전에는 메모리에 없다
→ 객체 생성 시 모든 일반 멤버들은 메모리에 생성
→ 객체, 즉 레퍼런스를 통해서 접근
메서드 호출 스택
기본형 변수와 참조형 변수
public class CallByTest{
int memberVar = 10;
static void change1(int var){
var += 10;
System.out.printf("change1: %d%n",var);
}
static void change2(CallByTest cbtl){
cbtl.memeberVar += 100;
System.out.printf("change2: %d%n",var);
}
public static void main(String[] args){
CallByTest cbt = new CallByTest();
cbt.memberVar = 5;
System.out.printf("change1 호출 전 memeberVar : %d%n",cbt.memberVar); //5
change1(cbt.memberVar); //얘는 값으로 전달 리턴되는 값이 없음 (지역변수)
System.out.printf("change1 호출 후 memeberVar : %d%n",cbt.memberVar); //5
change2(cbt); //얘는 객체의 주소 값을 메서드로 넣기 -> callByRefer
System.out.printf("change2 호출 후 memeberVar : %d%n",cbt.memberVar); //105
}
}
Emp ob = new Emp();
ob.setName("kim");
//객체 생성과 동시에 생성자를 통해 초기화
Emp ob = new Emp("lee");
작성 규칙: 메서드와 비슷하나 리턴 타입이 없고 이름은 클래스 이름과 동일
① 반드시 클래스 명과 동일해야 한다.
② 결과형(리턴값)이 없다.
③ 객체가 생성될때 자동 호출되며, 사용자가 임의로 호출할 수 없다
④ 멤버필드의 값을 초기화 한다
⑤ 생략하면 컴파일시 자동으로 default생성자를 만든다
⑥ 여러개의 생성자를 만들수 있다(생성자 overloading)
⑦ 생성자내부에서 첫번째라인에 this(매개변수)를 사용하여 다른 생성자를 호출할수 있다.
단, 1번만 호출이 가능하다
public class DefaultPerson{
String name;
int age;
boolean isHungry;
//public DefaultPerson() {} --생략된 기본 생성자
public static void main(String[] args){
DefaultPerson person = new DefaultPerson();
person.name = "홍길동"
person.age = 10;
person. isHungry = false;
}
}
public class ParameterPerson{
String name;
int age;
boolean isHungry;
ParameterPerson(String n, int a, boolean i){
name = n;
age = a;
isHungry = i;
}
public static void main(String[] args){
ParameterPerson person = new ParameterPerson("홍길동",10,true);
ParameterPerson person2 = new ParameterPerson(); //오류
}
}
1) this.
→ 참조 변수를 통해 객체의 멤버에 접근했던 것처럼 this를 이용해 자신의 멤버에 접근 가능
→ 로컬 변수와 멤버 변수의 이름이 동일할 경우 멤버 변수임을 명시적으로 나타냄
→ 명시적으로 멤버임을 나타낼 경우 사용
public class DefaultPerson{
String name = "아무개";
int age = 0;
boolean isHungry = true;
//public DefaultPerson() {} --생략된 기본 생성자
Person(String name, int age, boolean isHungry){
this.name = name;
this.age = age;
this.isHungry = isHungry;
}
void walk(){
this.isHungry = true;
System.out.println("뚜벅 뚜벅");
}
}

class Test{
int a;
int b;
static int c;
//static은 main실행하기 전에 한 번만 올려준다 static 변수는
//미리 메모리 영역에 올라감
static {
System.out.println("static 의 초기화 영역");
}
public Test(int a, int b, int c) {
this.a=a;
this.b=b;
Test.c = c;
System.out.println("객체의 초기화 영역");
}
public void view() {
System.out.println(a+" "+b+" "+c);
}
}
public class StaticEx1 {
public static void main(String[] args) {
Test ob1=new Test(1,2,3);
Test ob2=new Test(5,6,7);
//ob1.c = 100; //권장하지 않는다
Test.c = 100;
ob1.view();
ob2.view();
}
}
출력값
static 의 초기화 영역
객체의 초기화 영역
객체의 초기화 영역
1 2 100
5 6 100
2) this( )
public class ConstructorEx2 {
public ConstructorEx2() {
this("ABC",100);
System.out.println("Default Constructor");
}
public ConstructorEx2(String str, int n) {
System.out.println(str+ " "+n+" constructor");
}
public ConstructorEx2(String str) {
this(); //default 생성자 호출
System.out.println(str+" constructor");
}
public static void main(String[] args) {
new ConstructorEx2("ABC");
}
}
/*
ABC 100 constructor
default constructor
ABC constructor
*/
: 하나의 클래스에서 같은 이름의 메서드가 여러 번 구현된경우
사용하는 이유 ⇒ 메서드 이름을 절약하기 위해서 사용
ex) public void size(int a), public void size(int a, int b), public void size(double a, int b)
다 다른 함수 오버로딩 if 없었으면 함수 이름을 다 다르게 해야 오류가 안 난다.
(1) 메서드의 이름이 같아야 한다
(2) 매개변수의 갯수 또는 타입이 달라야 한다
(3) 매개변수는 같고 리턴타입이 다른경우는 오버로딩이 성립되지 않는다
(리턴타입은 오버로딩을 구현하는데 아무런 영향을 주지 못한다)
ex) void show(int a,int b){ }와 오버로딩인 메서드는?
①int show(int a,int b){ }
②void show(double a,double b){ }
③void show(int a){ }
④int show(char a){ }

** 객체지향 프로그래밍 코딩 Tip **