[Java] 2. 점프투자바 ch 4-5
Ch4
4-1 if
contain: List 자료형에 해당 아이템이 있는지 조사하는 contains 메서드가 있다.
ArrayList<String> pocket = new ArrayList<String>();
pocket.add("paper");
pocket.add("handphone");
pocket.add("money");
if (pocket.contains("money")) {
System.out.println("택시를 타고 가라");
}
else {
System.out.println("걸어가라");
}
4-5 for each
String[] numbers = {"one", "two", "three"};
for(String number: numbers) {
System.out.println(number);
}
Ch5
5-2 Class
a. instance variable(객체변수)
class Animal {
String name; // instance variable
static int age; // class variable(static variable)
}
public class Sample {
public static void main(String[] args) {
Animal cat = new Animal();
}
}
객체 변수는 공유되지 않는다
객체 변수의 값은 공유되지 않지만 07-3절에서 공부할 static을 이용하게 되면 객체 변수를 공유하도록 만들 수도 있다.
instance variable라 불리는 이유: 아래 코드에서 a1과 a2의 name변수가 초기화 되더라도 그 변수를 공유하지 않음.
반면, 클래스변수의 경우 a1,a2가 초기화시 age를 공유하게 되어서, 한 객체에서 값 변경시 다른 객체의 값도 바뀜
Animal a1 = new Animal();
Anumal a2 = new Anumal();
5-4 Call by Value, Call by Object
class Updater {
void update(int count) {
count++; // call by value -> 값이 증가하지 않음
}
}
class Updater {
void update(Counter counter) {
counter.count++; // call by object -> 값이 증가
}
}
class Counter {
int count = 0; // 객체변수
}
public class Sample {
public static void main(String[] args) {
Counter myCounter = new Counter();
System.out.println("before update:"+myCounter.count);
Updater myUpdater = new Updater();
myUpdater.update(myCounter);
//myUpdater.update(myCounter.count);
System.out.println("after update:"+myCounter.count);
}
}
Sample.java 파일 내에 Sample, Updater, Counter라는 클래스 3개가 등장했다. 이와 같이 하나의 java 파일 내에는 여러 개의 클래스를 선언할 수 있다. 단, 파일명이 Sample.java라면 Sample.java 내의 Sample 클래스는 public으로 선언하라는 관례(규칙)가 있다.
5-5. Inheritance
class Animal {
String name;
void setName(String name) {
this.name = name;
}
}
class Dog extends Animal {
void sleep() {
System.out.println(this.name+" zzz");
}
}
public class Sample {
public static void main(String[] args) {
Dog dog = new ...