2016년 8월 3일 수요일

Java 1-7 클래스, class, 오버로딩, 생성자, 전역변수, 지역변수


public class Main {

public static void main(String[] args) {

Game game = new Game();
game.dice(3);
game.dice(6,10);
game.dice(3L);

}

}

// 오버로드 테스트를 위한 동일한 이름의 메서드 2개 구현
// 같은 이름의 함수를 매개변수의 갯수나 타입이 다르면 만들 수 있다.
class Game{
/**
* dice
* @param type - 주사위의 모양, 면의 수
*/
void dice(int type) {
int dice = (int)(Math.random() * type) + 1;
System.out.println("주사위 : " + dice);
}
//오버로드는 메서드 이름은 같고 매개변수는 달라야 한다.
/**
* dice
* @param type - 주사위의 모양, 면의 수
* @param count - 주사위를 굴릴 횟수
*/
void dice(int type, int count){
int sumDice = 0;
for(int i = 0 ; i < count ; i++){
sumDice += (int)(Math.random() * type ) + 1;
}
System.out.println("주사위 : " + sumDice);

}
// 오버로드 구현할때 원형 메서드를 재활용 할 수도 있다.
void dice(long type) {
dice((int)type,1);
}


}
-----------------------------------------------------------------------------------

public class MainInit {

public static void main(String[] args) {

Game2 game = new Game2(3);
System.out.println(game.money);

}

}

class Game2{
int playerCount = 4;
long money = 0;
//생성자
//생성자는 무조건 클래스 이름으로만 만들고, 리턴값이 존재하지 않는다.
//생성자를 정의할때, 매개변수를 넣을 수도 있다. 하지만 매개변수가 존재하는 생성자를 만들면, 기본 생성자는 사라진다.
Game2(int playerCount){
this.playerCount = playerCount;
money = playerCount * 1000000;
}
// 매개변수생성자를 만들어서 기본생성자가 없어졌으므로, 기본생성자를 따로 정의해준다.
// 생성자도 오버로딩이 가능하다.
Game2(){
money = playerCount * 1000000;
}
}

댓글 없음:

댓글 쓰기