생성자 오버로딩(Constructor Overloading)
public class Student {
private int number;
private String name;
private int age;
Student() {
number = 100;
name = "New Student";
age = 24;
}
Student(int number, String name, int age) {
this.number = number;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [number = " + number + ", name = " + name + ", age = " + age + "]";
}
}
public class StudentTest {
public static void main(String[] args) {
Student obj1 = new Student();
System.out.println(obj1);
Student obj2 = new Student(111, "Kim", 25);
System.out.println(obj2);
}
}
Student [number = 100, name = New Student, age = 24]
Student [number = 111, name = Kim, age = 25]
this로 객체 나타내기
public class Date {
private int year;
private String month;
private int day;
public Date() { // 기본 생성자
this(1900, "1월", 1); // this()로 생성자를 호출하기
}
public Date(int year) { // 생성자
this(year, "1월", 1);
}
public Date(int year, String month, int day) { // 생성자
this.month = month; // this는 현재 객체를 가리킨다.
this.day = day;
this.year = year;
}
@Override
public String toString() {
return "Date [year = " + year + ", month = " + month + ", day = " + day + "]";
}
}
public class DateTest {
public static void main(String[] args) {
Date date1 = new Date(2015, "8월", 10);
Date date2 = new Date(2020);
Date date3 = new Date();
System.out.println(date1);
System.out.println(date2);
System.out.println(date3);
}
}
Date [year = 2015, month = 8월, day = 10]
Date [year = 2020, month = 1월, day = 1]
Date [year = 1900, month = 1월, day = 1]
시간 나타내기
public class Time {
private int hour; // 0 ~ 23
private int minute; // 0 ~ 59
private int second; // 0 ~ 59
// 첫 번째 생성자
public Time() {
this(0, 0, 0);
}
// 두 번째 생성자
public Time(int h, int m, int s) {
hour = ((h >= 0 && h < 24) ? h : 0); // 시간 검증
minute = ((m >= 0 && m < 60) ? m : 0); // 분 검증
second = ((s >= 0 && s < 60) ? s : 0); // 초 검증
}
// "시 : 분 : 초"의 형식으로 출력
public String toString () {
return String.format("%02d:%02d:%02d" + "\\n", hour, minute, second);
}
}
public class TimeTest {
public static void main(String[] args) {
// Time 객체를 생성하고 초기화한다.
Time t = new Time();
System.out.println("기본 생성자 호출 후 시간 : " + t.toString());
// 두 번째 생성자 호출
Time t2 = new Time(13, 27, 6);
System.out.println("두 번째 생성자 호출 후 시간 : " + t2.toString());
// 올바르지 않은 시간으로 설정해본다.
Time t3 = new Time(99, 66, 77);
System.out.println("올바르지 않은 시간 설정 후 시간 : " + t3.toString());
}
}
기본 생성자 호출 후 시간 : 00:00:00
두 번째 생성자 호출 후 시간 : 13:27:06
올바르지 않은 시간 설정 후 시간 : 00:00:00
인스턴스 초기화 블럭 이용하기
public class Car {
int speed;
Car() {
System.out.println("속도는 " + speed);
}
{
speed = 100; // 인스턴스 초기화 블럭. 생성자 호출보다 먼저 실행된다.
}
public static void main(String[] args) {
Car c1 = new Car();
Car c2 = new Car();
}
}
속도는 100
속도는 100
CircleTest
public class Point {
private int x, y;
public Point(int a, int b) {
x = a;
y = b;
}
@Override
public String toString() {
return "Point [x = " + x + ", y = " + y + "]";
}
}
public class Circle {
private int radius;
private Point center;
public Circle(Point p, int r) {
center = p;
radius = r;
}
@Override
public String toString() {
return "Circle [radius = " + radius + ", center = " + center + "]";
}
}
public class Circle {
private int radius;
private Point center;
public Circle(Point p, int r) {
center = p;
radius = r;
}
@Override
public String toString() {
return "Circle [radius = " + radius + ", center = " + center + "]";
}
}
Circle [radius = 10, center = Point [x = 25, y = 78]]
메서드로 기초형 변수가 전달되는 경우
public class MyCounter {
int value;
void inc(int a) {
a += 1;
}
/* int inc(int a) {
* a += 1;
* return a; */
}
public class MyCounterTest {
public static void main(String[] args) {
MyCounter obj = new MyCounter();
int x = 10;
obj.inc(x); // x의 복사본이 인수로 전달된다. 원본 x의 값은 10 그대로임.
System.out.println("x = " + x);
/* int rtn = obj.inc(x);
* System.out.println("rtn = " + rtn); */ // result rtn = 11
}
}
x = 10
메서드로 객체가 전달되는 경우
public class MyCounter1 {
int value = 0;
void inc(MyCounter1 ctr) {
ctr.value = ctr.value + 1;
}
}
public class MyCounter1 {
int value = 0;
void inc(MyCounter1 ctr) {
ctr.value = ctr.value + 1;
}
}
obj.value = 0
obj.value = 1
메서드로 배열이 전달되는 경우
public class Arrayproc {
void inc(int[] array) {
for(int i = 0; i < array.length; i++)
array[i] += 1;
}
}
public class ArrayprocTest {
public static void main(String[] args) {
int[] list = { 1, 2, 3, 4, 5 };
Arrayproc obj = new Arrayproc();
for(int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
System.out.println(" ");
obj.inc(list);
for(int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
}
}
1 2 3 4 5
2 3 4 5 6
메서드에서 객체를 반환하기(return)
public class Box2 {
int width, length, height;
int volume;
Box2(int w, int l, int h) {
width = w;
length = l;
height = h;
volume = w * l * h;
}
Box2 whosLargest(Box2 box1, Box2 box2) {
if(box1.volume > box2.volume)
return box1;
else {
return box2;
}
}
}
public class Box2Test {
public static void main(String[] args) {
Box2 obj1 = new Box2(10, 20, 50);
Box2 obj2 = new Box2(10, 30, 30);
Box2 largest = obj1.whosLargest(obj1, obj2);
System.out.println("(" + largest.width + ", " +
largest.length + ", " + largest.height + ")");
}
}
(10, 20, 50)
static member(정적 멤버)
인스턴스 멤버 vs 정적 멤버
public class Car {
private String model;
private String color;
private int speed;
// 자동차의 시리얼 번호
private int id;
// 실체화된 Car1 객체의 개수를 위한 정적 변수
static int numbers = 0; // 정적(공유) 멤버
public Car1(String m, String c, int s) {
model = m;
color = c;
speed = s;
// 자동차의 개수를 증가하고 id에 대입한다.
id = ++numbers;
}
// 정적 메소드
public static int getNumberOfCars() {
return numbers; // OK!
}
}
public class CarTest {
public static void main(String[] args) {
Car1 c1 = new Car1("S600", "White", 80); // 첫 번째 생성자 호출
Car1 c2 = new Car1("E500", "Blue", 20); // 두 번째 생성자 호출
int n = Car1.getNumberOfCars(); // 정적 메소드 호출
// int n = Car1.numbers; // 정적 변수 Car라는 Class명을 사용하였다.
System.out.println("지금까지 생성된 자동차 수 = " + n);
}
}
지금까지 생성된 자동차 수 = 2
정적 블럭 호출
static int x; // 정적 변수
int y;
static {
x = 10;
System.out.println("정적 블럭이 호출되었음! ");
}
}
static int x; // 정적 변수
int y;
static {
x = 10;
System.out.println("정적 블럭이 호출되었음! ");
}
}
정적 블럭이 호출되었음!
10
InnerTest
public class OuterClass {
private int value = 10;
class InnerClass {
public void myMethod() {
System.out.println("외부 클래스의 private 변수 값 : " + value);
}
}
OuterClass() {
InnerClass obj = new InnerClass();
obj.myMethod();
}
}
public class InnerClassTest {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
}
}
외부 클래스의 private 변수 값 : 10