생성자는 자바의 기초이지만 정말 중요하고 또 중요한것이라고 볼 수 있다.
- 생성자
CarOrder.java
public class CarOrder {
public static void main(String[] args) {
Car car1 = new Car();
car1.color = "green";
car1.price = 2000;
System.out.println(car1.color + " " + car1.price);
}
}
Car.java
public class Car {
String color;
int price;
public Car() {
}
}
CarOrder에서 Car에 대한 객체를 new하면 생성자를 호출한다.
Car에 있는 public Car()는 매개변수도 없고 내용도 비어있다. 하지만 CarOrder에서 car1. 으로 직접 지역변수에 값을 지정해주고 있기 때문에 결과는
이 나오는 것을 볼 수 있다.
- Default 생성자
위 코드에 Car.java를 바꿔보겠다.
public class Car {
String color;
int price;
}
이렇게 바꿔줄 경우에 CarOrder.java가 수행이 되는가 ? 잘 된다. 이유는 자바를 Default생성자를 선언하지 않아도 자동으로 가지고 있기 때문이다. 따라서 우리가 직접 짜지는 않았지만 생성자가 아무것도 없을경우 Default생성자가 수행되면서 컴파일이 완전하다.
- 생성자로 값 할당하기 & 자동 소스코드 Generate
소스코드 빈곳에 오른쪽 마우스클릭 -> Source에 보면 자동 Generate기능이 있다. 여기서 생성자 자동생성은 Generate Constructor using Fields... 이다. 이것을 클릭해주면
이런식으로 col..(color) pri..(price)가 체크가 되어있다. 값을 두개다 할당하고 싶으면 둘다 체크후 Generate! 그럼 소스코드가
public class Car {
String color;
int price;
public Car(String color, int price) {
super();
this.color = color;
this.price = price;
}
}
생성이 아주 잘된다. 여기서 궁금한점 ! super(); 는 뭘까? super();는 부모의 Default생성자를 부를때 사용하는 것이다. 쓰지 않아도 자동으로 실행되는 코드이다. 부모가 뭘까? 나중에 상속을 배우면 자세히 알아보도록 하고 super()는 아직 몰라도 되니 주석처리하자.
그럼 이제 CarOrder.java를 바꿔야 겠지 ?
public class CarOrder {
public static void main(String[] args) {
Car car1 = new Car("green",2000);
System.out.println(car1.color + " " + car1.price);
}
}
이렇게 해주면 생성과 동시에 지역변수에 값을 삽입할수 있다! 정말 쉽쥬 ?
어쨌든.. 다음으로 넘어가자
- 생성자 오버라이딩
생성자 오버라이딩이란 ? 말그대로 오버해서 읽는거다. 이게 맞나 ㅋㅋ
잔말말고 소스코드로 확인해보자
ObjectTest.java
public class ObjectTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
method1();
}
private static void method1() {
// TODO Auto-generated method stub
Computer c1;
Computer c2;
c1 = new Computer("B100",200,"MAC");
c2 = new Computer();
System.out.println(c1.company);
System.out.println(c1.model);
System.out.println(c1.price);
System.out.println(c1.os);
System.out.println("-----------------");
System.out.println(c2.company);
System.out.println(c2.model);
System.out.println(c2.price);
System.out.println(c2.os);
}
}
Computer.java
public class Computer {
String model;
int price;
String os;
String company = "Samsung";
Computer(){
this(null,0,null);
}
Computer(String model,int price){
this(model,price,null);
}
//코드를 여기로 모으려고 하는 생성자
Computer(String model,int price,String os){
this.model = model;
this.price = price;
this.os = os;
}
}
main메소드에서 생성을 할때 c1 처럼 매개변수를 3개를 써서 생성을 할수도있고 c2처럼 매개변수가 아예 없을수도 또는 1개일수도 2개일수도 있다. 이것을 미연에 방지 하기위해 오버라이딩을 하는 것이다. 하지만 오버라이딩이 이렇게 하는것이 아닌
public class Computer {
String model;
int price;
String os;
String company = "Samsung";
Computer(){
this.model = null;
this.price = 0;
this.os = null;
}
Computer(String model,int price){
this.model = model;
this.price = price;
this.os = null;
}
Computer(String model,int price,String os){
this.model = model;
this.price = price;
this.os = os;
}
}
이렇게 모든 경우의수를 전부 this.으로 할당을 받는것은 정말 불필요한 코드라고 할 수 있다. 이러한 것을 해결한것이 바로 위 코드이다. 매개변수에 들어온 값을 this();로 해서 최상위 생성자 즉, 매개변수가 가장 많은 Computer(String model,int price,String os)로 매개변수를 모아서 생성하는 습관을 들여야 한다. 그게 효율적인 코드인거니깐
이렇게 생성자에 대해 간단히 알아보았다!