객체(Object)
객체를 정의 -> 기능 구현 -> 각 객체간의 협력을 구현
public class Student {
int studentNumber;
String studentName;
...
int add(int num1, int num2) {
int result;
result = num1 + num2;
return result;
}
메서드(method)
인스턴스 (instance)
...
Student studentLee = new Student(12345, "Lee", 3);
...
public class Student {
public int studentNumber;
public String studentName;
public int grade;
public Student(int studentNumber, String studentName, int grade) {
this.studentNumber = studentNumber;
this.studentName = studentName;
this.grade = grade;
}
public class UserInfo {
public String userId;
public String userPassWord;
public String userName;
public String userAddress;
public String phoneNumber;
public UserInfo(){}
public UserInfo(String userId, String userPassWord, String userName) {
this.userId = userId;
this.userPassWord = userPassWord;
this.userName = userName;
}
접근 제어 지시자(access modifier)
get()/ set() 메서드
private 으로 선언된 멤버 변수 (필드)에 대해 접근, 수정할 수 있는 메서드를 public으로 제공
정보 은닉
객체 오류를 방지하고 더 효율적인 객체 활용을 위해 외부에서 접근 가능한 정보를 최소화
package ch10;
public class BirthDay {
private int day;
private int month;
private int year;
private boolean isValid;
public int getDay() {
return day;
}
public void setDay(int day) {
switch(month){
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
if(day < 1 || day > 31) {
isValid = false;
} else {
isValid = true;
this.day = day;
}
break;
case 2:
if(day < 1 || day > 28) {
isValid = false;
} else {
isValid = true;
this.day = day;
}
break;
case 4: case 6: case 9: case 11:
if(day < 1 || day > 30) {
isValid = false;
} else {
isValid = true;
this.day = day;
}
break;
};
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
if( month < 1 || month > 12)
{
isValid = false;
} else {
isValid = true;
this.month = month;
}
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public void showDate() {
if(isValid) {
System.out.println(year + "년 " + month + "월 " + day + "일 입니다.");
} else {
System.out.println("유효하지 않은 날짜입니다.");
}
}
}
꼭 필요한 정보와 기능만 외부에 오픈함
각각의 메서드나 멤버 변수를 접근함으로써 발생하는 오류를 최소화
this
인스턴스 자신의 메모리를 가리킴
객체 간에는 협력이 이루어짐
public class Student {
String studentName;
int money;
public Student(String studentName, int money) {
this.studentName = studentName;
this.money = money;
}
public void takeBus(Bus bus) {
bus.take(1000);
this.money -= 1000;
}
public void takeSubway(Subway subway) {
subway.take(1200);
this.money -= 1200;
}
public void showInfo() {
System.out.println(studentName + "님의 남은 돈은 " + money + "원 입니다");
}
}
public class Bus {
int busNumber;
int passengerCount;
int money;
public Bus(int busNumber) {
this.busNumber = busNumber;
}
public void take(int money) {
this.money += money;
passengerCount++;
}
public void showBusInfo() {
System.out.println(busNumber + "번 버스의 승객은 " + passengerCount + "명 이고, 수입은 " + money + "원 입니다");
}
}
public class Subway {
int lineNumber;
int passengerCount;
int money;
public Subway(int lineNumber) {
this.lineNumber = lineNumber;
}
public void take(int money) {
this.money += money;
passengerCount++;
}
public void showSubwayInfo() {
System.out.println(lineNumber + "번 지하철의 승객은 " + passengerCount + "명 이고, 수입은 " + money + "원 입니다");
}
}
public class TakeTransTest {
public static void main(String[] args) {
Student studentJ = new Student("James", 5000);
Student studentT = new Student("Tomas", 10000);
Bus bus100 = new Bus(100);
Subway subwayGreen = new Subway(2);
studentJ.takeBus(bus100);
studentT.takeSubway(subwayGreen);
studentJ.showInfo();
studentT.showInfo();
bus100.showBusInfo();
subwayGreen.showSubwayInfo();
}
}
public class Taxi {
String taxiName;
int money;
public Taxi(String taxiName) {
this.taxiName = taxiName;
}
public void take(int money) {
this.money += money;
}
public void showTaxiInfo() {
System.out.println(taxiName + " 수입은 " + money + "원 입니다.");
}
}
public class Student {
...
public void takeTaxi(Taxi taxi) {
taxi.take(10000);
this.money -= 10000;
}
}
public class TakeTransTest {
...
Student studentE = new Student("Edward", 20000);
Taxi newTaxi = new Taxi("잘 간다 운수택시");
studentE.takeTaxi(newTaxi);
studentE.showInfo();
newTaxi.showTaxiInfo();
}
여러 인스턴스가 공유하는 기준 값이 필요한 경우
ex) 학번, 사번 등등
static int serialNum~
인스턴스가 한 개만 생성되어야 하는 경우 사용하는 디자인 패턴
public class Car {
public static int serialNumber = 10000;
private int carNum;
public int getCarNum() {
return carNum;
}
public void setCarNum(int carNum) {
this.carNum = carNum;
}
public Car() {
serialNumber++;
carNum = serialNumber;
}
}
public class CarFactory {
public static CarFactory instance = new CarFactory();
public CarFactory() {
}
public static CarFactory getInstance() {
if( instance == null) {
instance = new CarFactory();
}
return instance;
}
public Car createCar() {
Car car = new Car();
return car;
}
}
객체 배열의 경우엔 요소가 되는 객체의 주소가 들어갈(4바이트, 8바이트) 메모리만 할당
객체 배열 복사하기
** 얕은 복사
...
System.arraycopy(library, 0, copyLibrary, 0, 5);
...
** 깊은 복사
...
copyLibaray[0] = new Book();
copyLibaray[1] = new Book();
copyLibaray[2] = new Book();
copyLibaray[3] = new Book();
copyLibaray[4] = new Book();
for(int i = 0; i< library.length; i++) {
copyLibaray[i].setTitle(library[i].getTitle());
copyLibaray[i].setAuthor(library[i].getAuthor());
}
library[0].setTitle("나목");
library[0].setAuthor("박완서");
...
int[][] arr = new int[2][3];
자료형 배열이름 = new 자료형[행개수][열개수]
StudentTest
Student
Subject