publicclassCar{// Attributes (fields) - the STATE of the objectprivateStringbrand;privateStringmodel;privateStringcolor;privatebooleanisRunning;// Constructor - special method to initialize new objectspublicCar(Stringbrand,Stringmodel,Stringcolor){this.brand=brand;this.model=model;this.color=color;this.isRunning=false;// default value}// Methods - the BEHAVIOR of the objectpublicvoidstartEngine(){this.isRunning=true;System.out.println("The "+color+" "+brand+" "+model+"'s engine is now running.");}publicvoidstopEngine(){this.isRunning=false;System.out.println("The engine has been stopped.");}publicvoidhonk(){System.out.println("Beep Beep!");}// Getter methods to access private fieldspublicStringgetBrand(){returnbrand;}publicStringgetModel(){returnmodel;}publicStringgetColor(){returncolor;}publicbooleanisRunning(){returnisRunning;}}
➕ 정적 멤버가 있는 클래스와 객체의 차이점은?
클래스는 실제 값이 있다기보다는 생성될 객체들에 포함될 요소들을 정의하는 역할을 한다.
그렇다면 실제 값, 즉 정적 값이 있는 클래스는 어떨까?
클래스에 실제 값이 있으니까 객체라고 할 수 있을까?
클래스에 있는 값은 상태가 없다.
클래스의 정적 값들은 유틸리티, 상수, 공유할 데이터로 쓰인다.
정적 값이 있더라도 인스턴스처럼 쓰이지 않는다. 값이 변하지 않아서 실생활을 나타낼 수 없다.
예시: 자동차의 경우 제조사, 생성된 자동차의 총 수량 등을 설정할 수 있다.
publicclassCar{// Static fields (class-level) - shared by all instancespublicstaticinttotalCarsCreated=0;publicstaticfinalStringMANUFACTURER="AutoCorp";// Static methodpublicstaticvoiddisplayManufacturerInfo(){System.out.println("Manufacturer: "+MANUFACTURER);System.out.println("Total cars created: "+totalCarsCreated);}}
용례
publicclassMain{publicstaticvoidmain(String[]args){// Access static field without creating an instanceSystem.out.println("Manufacturer: "+Car.MANUFACTURER);// Access static field to see it's shared across all instancesSystem.out.println("Total cars: "+Car.totalCarsCreated);// Call static methodCar.displayManufacturerInfo();}}
인스턴스와 객체의 값은 상태가 있다.
저마다의 신원과 상태가 있는 엔티티를 모델링할 목적으로 쓰인다.
예시: 자동차의 경우 모델, 색, 출시 년도 등을 포함할 수 있다.
publicclassCar{// Instance fields (object-level) - unique to each instancepublicStringmodel;publicStringcolor;publicintyear;// ConstructorpublicCar(Stringmodel,Stringcolor,intyear){this.model=model;this.color=color;this.year=year;totalCarsCreated++;// Increment static counter for each new car}// Instance methodpublicvoiddisplayCarInfo(){System.out.println("Model: "+model+", Color: "+color+", Year: "+year);}}
용례
publicclassMain{publicstaticvoidmain(String[]args){// Create instances (objects)Carcar1=newCar("Sedan","Red",2023);Carcar2=newCar("SUV","Blue",2024);// Use instance methodscar1.displayCarInfo();car2.displayCarInfo();}}
객체(Object)
특징
“객체와 객체를 만든 클래스와의 관련성”이라는 맥락을 제외하고는 인스턴스와 차이가 없다.
객체는 메모리를 차지한다. 즉 메모리에 할당된다.
➕ 인스턴스와의 맥락적 차이 예시
✅ myCar는 Car의 인스턴스이다. → 클래스와 객체의 관련성을 보여주어 자연스러움
✅ myCar은 객체이다. → 대상이 무엇인지 나타내어 자연스러움
❌ myCar는 Car의 객체이다. → 아주 틀린 말은 아니지만 부자연스러움
객체 → 정체성을 나타내는 용어. “그 사람은 목수이다”, “저건 탁자이다”
인스턴스: 관계성을 나타내는 용어. “그 사람은 윤희의 딸이다”, “저 강아지는 철수의 반려동물이다”
정체성을 나타내는 용어를 관계성을 설명하는 맥락에서 사용했으니 어색한 것!
코드 예시
예시
모든 객체는 클래스가 정의한 필드들에 대한 자신만의 데이터를 지닌다.
publicclassMain{publicstaticvoidmain(String[]args){// Creating INSTANCES (OBJECTS) of the Car class// Each 'new' keyword creates a new instanceCarmyCar=newCar("Tesla","Model 3","red");CaryourCar=newCar("Toyota","Camry","blue");CarcompanyCar=newCar("Ford","Explorer","white");// These are all INSTANCES of the Car class// They are also OBJECTS// Each instance has its own separate dataSystem.out.println("My car: "+myCar.getColor()+" "+myCar.getBrand());System.out.println("Your car: "+yourCar.getColor()+" "+yourCar.getBrand());// They can perform actions independentlymyCar.startEngine();// Only myCar's engine startsyourCar.honk();// Only yourCar honksSystem.out.println("Is my car running? "+myCar.isRunning());// trueSystem.out.println("Is your car running? "+yourCar.isRunning());// false}}
인스턴스(Instance)
특징
“객체와 객체를 만든 클래스와의 관련성”이라는 맥락을 제외하고는 인스턴스와 차이가 없다.
모든 인스턴스는 객체이다.
인스턴스는 메모리를 차지한다. 즉 메모리에 할당된다.
➕ 서비스를 하는 실무에서는 인스턴스와 객체를 엄밀하게 구분하지 않는다
개발자가 “어떤 클래스에서 인스턴스를 만들었어”라고 하든 “어떤 클래스에서 객체를 만들었어”라고 하든 말의 의도가 같다.
대부분의 프로그래밍 언어에서 문서나 구문에서 둘의 차이를 강제하지 않는다.
학술적 분야, 기술 인터뷰 등의 경우는 둘을 구분하기도 한다.
코드 예시
예시
모든 인스턴스는 클래스가 정의한 필드들에 대한 자신만의 데이터를 지닌다.
publicclassMain{publicstaticvoidmain(String[]args){// Creating INSTANCES (OBJECTS) of the Car class// Each 'new' keyword creates a new instanceCarmyCar=newCar("Tesla","Model 3","red");CaryourCar=newCar("Toyota","Camry","blue");CarcompanyCar=newCar("Ford","Explorer","white");// These are all INSTANCES of the Car class// They are also OBJECTS// Each instance has its own separate dataSystem.out.println("My car: "+myCar.getColor()+" "+myCar.getBrand());System.out.println("Your car: "+yourCar.getColor()+" "+yourCar.getBrand());// They can perform actions independentlymyCar.startEngine();// Only myCar's engine startsyourCar.honk();// Only yourCar honksSystem.out.println("Is my car running? "+myCar.isRunning());// trueSystem.out.println("Is your car running? "+yourCar.isRunning());// false}}
✨ 많은 이들이 통과하는 “대입”의 문. 근데… 어느 문으로 들어가지?
우리나라 고등학생의 70% 이상은 대학에 진학한다. 대부분의 학부모와 학생들은 “어느 대학교에 갈 수 있을까”를 가장 주요하게 신경쓴다. 우리나라 대학교는 서열이 있고, 그들은 이 서열에 민감하다.
나도 대학...