4.오버로딩(overloading)
4.1 오버로딩이란?
- 메서드의 매개변수의 개수 도는 타입이 다르면 같은 이름의 메서드 사용 가능
4.2 오버로딩 조건
- 메서드 이름이 같아야 한다
- 매개변수의 개수 또는 타입이 달라야 한다
- 리턴 타입은 상관 없음(매개변수에 의해서만 구별)
4.3 오버로딩의 예
- 어떤 매개변수를 지정해도 출력하는 println() // API 에서 찾아 보자
4.4 오버로딩의 장점
- 메서드를 하나의 이름으로 사용하므로 사용이 쉽고 오류의 가능성이 줄어듬
package ch06;
class OverloadingTest {
public static void main(String args[]) {
MyMath3 mm = new MyMath3();
System.out.println("mm.add(3, 3) 결과:" + mm.add(3,3));
System.out.println("mm.add(3L, 3) 결과: " + mm.add(3L,3));
System.out.println("mm.add(3, 3L) 결과: " + mm.add(3,3L));
System.out.println("mm.add(3L, 3L) 결과: " + mm.add(3L,3L));
int[] a = {100, 200, 300};
System.out.println("mm.add(a) 결과: " + mm.add(a));
}
}
class MyMath3 {
int add(int a, int b) {
System.out.print("int add(int a, int b) - ");
return a+b;
}
long add(int a, long b) {
System.out.print("long add(int a, long b) - ");
return a+b;
}
long add(long a, int b) {
System.out.print("long add(long a, int b) - ");
return a+b;
}
long add(long a, long b) {
System.out.print("long add(long a, long b) - ");
return a+b;
}
int add(int[] a) { // 배열의 모든 요소의 합을 결과로 돌려준다.
System.out.print("int add(int[] a) - ");
int result = 0;
for(int i=0; i < a.length;i++) {
result += a[i];
}
return result;
}
}
4.5 가변인자(varargs)와 오버로딩
- 타입... 변수명
- 매개변수 중 가장 마지막에 선언
package ch06;
class VarArgsEx {
public static void main(String[] args) {
String[] strArr = { "100", "200", "300" };
System.out.println(concatenate("", "100", "200", "300"));
System.out.println(concatenate("-", strArr));
System.out.println(concatenate(",", new String[]{"1", "2", "3"}));
System.out.println("["+concatenate(",", new String[0])+"]");
System.out.println("["+concatenate(",")+"]");
}
static String concatenate(String delim, String... args) {
String result = "";
for(String str : args) {
result += str + delim;
}
return result;
}
/*
static String concatenate(String... args) {
return concatenate("",args);
}
*/
} // class
5.생성자
5.1 생성자란
- 인스턴스 생성시 호출되는
인스턴스 초기화 메서드
- 생성자의 이름은 클래스이 이름과 같아야 한다
- 리턴값이 없다
- 오버로딩 가능
Card c = new Card() 수행과정
- 연산자 new에 의해서 메모리(heap)에 Card 클래스의 인스턴스 생성
- 생성자 Card() 호출 수행
- Card인스턴스 주소 c에 저장
5.2 기본 생성자
클래스이름() {}
- 컴파일러가 제공하는 기본 생성자
- 매개변수가 하나도 없어야 한다
package ch06;
class Data1 {
int value;
}
class Data2 {
int value;
Data2(int x) { // 매개변수가 있는 생성자.
value = x;
}
}
class ConstructorTest {
public static void main(String[] args) {
Data1 d1 = new Data1();
//Data2 d2 = new Data2(); // compile error발생
Data2 d2 = new Data2(3); // compile error발생
}
}
5.3 매개변수가 있는 생성자
package ch06;
class Car {
String color; // 색상
String gearType; // 변속기 종류 - auto(자동), manual(수동)
int door; // 문의 개수
Car() {}
Car(String c, String g, int d) {
color = c;
gearType = g;
door = d;
}
}
class CarTest {
public static void main(String[] args) {
Car c1 = new Car();
c1.color = "white";
c1.gearType = "auto";
c1.door = 4;
Car c2 = new Car("white", "auto", 4);
System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType+ ", door="+c1.door);
System.out.println("c2의 color=" + c2.color + ", gearType=" + c2.gearType+ ", door="+c2.door);
}
}
5.4 생성자에서 다른 생성자 호출하기 - this(), this
- 생성자의 이름으로 클래스이름 대신 this 사용
- 한 생성자에서 다른 생성자 호출 시는 반드시 첫 줄에서만 호출 가능
- 인스턴스 변수에 this 사용
package ch06;
class Car2 {
String color; // 색상
String gearType; // 변속기 종류 - auto(자동), manual(수동)
int door; // 문의 개수
Car2() {
this("white", "auto", 4);
}
Car2(String color) {
this(color, "auto", 4);
}
Car2(String color, String gearType, int door) {
this.color = color;
this.gearType = gearType;
this.door = door;
}
}
class CarTest2 {
public static void main(String[] args) {
Car2 c1 = new Car2();
Car2 c2 = new Car2("blue");
System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType+ ", door="+c1.door);
System.out.println("c2의 color=" + c2.color + ", gearType=" + c2.gearType+ ", door="+c2.door);
}
}
5.5 생성자를 이용한 인스턴스 복사
- 현재 사용하고 있는 인스턴스와 같은 상태를 갖는 인스턴스 만들 때 사용
package ch06;
class Car3 {
String color; // 색상
String gearType; // 변속기 종류 - auto(자동), manual(수동)
int door; // 문의 개수
Car3() {
this("white", "auto", 4);
}
Car3(Car3 c) { // 인스턴스의 복사를 위한 생성자.
color = c.color;
gearType = c.gearType;
door = c.door;
}
Car3(String color, String gearType, int door) {
this.color = color;
this.gearType = gearType;
this.door = door;
}
}
class CarTest3 {
public static void main(String[] args) {
Car3 c1 = new Car3();
Car3 c2 = new Car3(c1); // c1의 복사본 c2를 생성한다.
System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType+ ", door="+c1.door);
System.out.println("c2의 color=" + c2.color + ", gearType=" + c2.gearType+ ", door="+c2.door);
c1.door=100; // c1의 인스턴스변수 door의 값을 변경한다.
System.out.println("c1.door=100; 수행 후");
System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType+ ", door="+c1.door);
System.out.println("c2의 color=" + c2.color + ", gearType=" + c2.gearType+ ", door="+c2.door);
}
}
인스턴스 생성시 고려해야할 사항 2가지
클래스 : 어떤 클래스의 인스턴스를 생성 할 것인가
생성자 : 선택한 클래스의 어떤 생성자로 생성 할 것인가
6.변수의 초기화
6.1 변수의 초기화
- 멤버변수는 자동으로 초기화
- 지역변수는 사용하기 전 반드시 초기화 해야 함
자료형 | 기본값 |
---|---|
boolean | false |
char | '\u0000' |
byte, short, ing | 0 |
Long | 0L |
float | 0.0f |
double | 0.0 |
참조형 변수 | null |
6.2 명시적 초기화
- 변수를 선언과 동시에 초기화 하는 것
class Car{
int door = 4; // 기본형 변수 초기화
Engine e = new Engine(); // 참조형 변수 초기화
}
6.3 초기화 블럭(initialization block)
- 클래스 초기화 블럭 : 클래스 변수의 복잡한 초기화에 사용
- 인스턴스 초기화 불럭 : 인스턴스 변수의 복잡한 초기화에 사용
package ch06;
class BlockTest {
static { // 제일 먼저 실행됨
System.out.println("static { }");
}
{
System.out.println("{ }");
}
public BlockTest() {
System.out.println("생성자");
}
public static void main(String args[]) {
System.out.println("BlockTest bt = new BlockTest(); ");
BlockTest bt = new BlockTest();
System.out.println("BlockTest bt2 = new BlockTest(); ");
BlockTest bt2 = new BlockTest();
}
}
6.4 멤버변수의 초기화 순서와 순서
- 클래스변수 초기화시점 : 클래스가 처음 로딩될 때 단 한번 초기화
- 인스턴스변수 초기화시점 : 인스턴스가 생성 될때 마다 각 인스턴스별로 초기화
- 클래스변수의 초기화 순서 : 기본값 -> 명시적 초기화 -> 클래스 초기화 블럭
- 인스턴스변수의 초기화 순서 : 기본값 -> 명시적 초기화 -> 인스턴스 초기화 블럭 -> 생성자
package ch06;
class Product {
static int count = 0; // 생성된 인스턴스의 수를 저장하기 위한 변수
int serialNo; // 인스턴스 고유의 번호
{
++count;
serialNo = count;
}
public Product() {} // 기본생성자, 생략가능
}
class ProductTest {
public static void main(String args[]) {
Product p1 = new Product();
Product p2 = new Product();
Product p3 = new Product();
System.out.println("p1의 제품번호(serial no)는 " + p1.serialNo);
System.out.println("p2의 제품번호(serial no)는 " + p2.serialNo);
System.out.println("p3의 제품번호(serial no)는 " + p3.serialNo);
System.out.println("생산된 제품의 수는 모두 "+Product.count+"개 입니다.");
}
}
package ch06;
class Document {
static int count = 0;
String name; // 문서명(Document name)
Document() { // 문서 생성 시 문서명을 지정하지 않았을 때
this("제목없음" + ++count);
}
Document(String name) {
this.name = name;
System.out.println("문서 " + this.name + "가 생성되었습니다.");
}
}
class DocumentTest {
public static void main(String args[]) {
Document d1 = new Document();
Document d2 = new Document("자바.txt");
Document d3 = new Document();
Document d4 = new Document();
}
}
이전글
[JAVA] - chap 06 객체지향 프로그래밍 I(object-oriented programming I)_1
[JAVA] - chap 06 객체지향 프로그래밍 I(object-oriented programming I)_2
[JAVA] - chap 06 객체지향 프로그래밍 I(object-oriented programming I)_3
'JAVA > 객체지향 프로그래밍 I' 카테고리의 다른 글
객체지향 프로그래밍 I(object-oriented programming I)_3 (2) | 2018.08.17 |
---|---|
객체지향 프로그래밍 I(object-oriented programming I)_2 (0) | 2018.08.17 |
객체지향 프로그래밍 I(object-oriented programming I)_1 (1) | 2018.08.17 |