최신글
hyeonga_code
Java_33_메소드 오버로딩 본문
반응형
- 메소드 오버로딩 : 메소드의 이름은 같으나 매개 변수의 개수가 다른 경우
'Student.java'
'''
// 6. 메소드 오버로딩
public Student(String studentName) {
this.studentName = studentName;
}
public Student(int studentID, String studentName, String address, int grade) {
this.studentID = studentID;
this.studentName = studentName;
this.address = address;
this.grade = grade;
}
'''
=====
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
package oop.basic;
//모든 클래스는 패키지 안에 생성합니다.
// 기본형, 메소드의 조합입니다.
public class Student {
// 모든 함수_메소드는 클래스 안에 작성합니다.
// 실행하기 위함이 아닌 spec을 작성하기 위함이므로 main()함수를 작성하지 않습니다.
/*
- 추상화
- 학생 spec 작성하기
- 학번
- 이름
- 학년
- 주소
*/
// 1. 멤버 변수를 선언합니다.
private int studentID; // 한 번 지정하면 변경할 수 없도록 private으로 지정합니다.
String studentName;
private int grade; // 클래스 외부에서 접근이 불가능합니다.
String address;
// 5. 생성자 : 멤버 변수를 초기화 할 때 사용되는 메서드 입니다.
public Student() {
/*
- 기본 생성자
- 생성자를 하나라도 생성하게 되면 기본 생성자를 자동으로 만들어주지 않습니다.
- 직접 작성해야 합니다.
*/
}
public Student(int studentID) {
/*
- 생성자의 이름은 클래스의 이름과 동일하게 작성합니다.
- 초기화만 진행하기 때문에 반환값이 없습니다.
- 매개 변수의 이름은 자유롭게 작성해도 되지만 멤버 변수의 이름과 동일하게 작성합니다.
*/
this.studentID = studentID;
/*
'클래스에서 사용하는 멤버 변수 이름' = '생성자에서 선언한 매개 변수 이름';
- 멤버 변수와 매개 변수의 이름을 동일하게 작성하는 경우가 많으므로 구분이 어렵습니다.
> 멤버 변수 앞에 this를 사용하여 구분할 수 있게 작성합니다.
- this : Heap 공간에 생성된 각각의 객체 자신을 의미합니다.
*/
}
/*
- 생성자를 작성하게 되면 new Student() 메소드로 작성했던 코드들이 오류가 발생합니다.
- 기본 생성자이기 때문에 작성한 생성자로 다시 작성해야 합니다.
*/
// 6. 메소드 오버로딩
public Student(String studentName) {
this.studentName = studentName;
}
public Student(int studentID, String studentName, String address, int grade) {
this.studentID = studentID;
this.studentName = studentName;
this.address = address;
this.grade = grade;
}
// 2. 학생의 이름, 주소 출력 메소드 선언
public void showStudentInfo() {
System.out.println("Name : " + studentName);
System.out.println("Address : " + address);
System.out.println("ID : " + studentID);
}
// 3. 멤버 변수 접근
public String getStudentName() {
return studentName; // Student 클래스에 선언된 멤버 변수의 값을 반환합니다.
}
public void setStudentName(String studentName) {
// studentName 을 매개 변수로 받아 함수를 호출하고 반환값은 없습니다.
this.studentName = studentName;
/*
this.studentName : Student 클래스에 선언된 멤버 변수입니다.
=
studentName : 받아온 매개 변수입니다.
*/
// String studentName1 / studentName = studentName1 로 변경
}
// 4. 멤버 변수 접근 제한
public int getGrade() { // getter 메소드를 통해 값에 접근할 수 있습니다.
return grade;
}
public void setGrade(int grade1) {
if( grade1>0 && grade1<4 ) {
grade = grade1;
} else { // 규정에 맞지 않는 데이터를 입력 했을 경우
System.out.println("+Grade : between 1 and 3");
}
}
}
|
'StudentApp.java'
'''
Student student5 = new Student("stName5");
student5.showStudentInfo();
Student student6 = new Student(2,"stName6","Address 456-456",2);
student6.showStudentInfo();
'''
=====
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
|
package oop.basic;
//모든 클래스는 패키지 안에 생성합니다.
public class StudentApp {
// 모든 함수_메소드는 클래스 안에 작성합니다.
// 별칭을 지정합니다.
static void printInfo(Student student) {
/*
- Scope 내의 코드에 대해 별칭을 지정하여 실행할 수 있습니다.
'별칭' {
별칭으로 지정할 코드
}
- 문제
- 외부에서 Scope 내의 변수에 접근할 수 없습니다.
>>> 별칭은 내부 변수를 초기화 하는 매개 변수_()를 제공합니다.
- 매개 변수 이름은 내부 변수 이름과 동일하게 작성합니다.
'별칭'('매개 변수 이름') {
별칭으로 지정할 코드
}
>>> Compile 하기 위해 매개 변수의 데이터 타입을 알려주어야 합니다.
'별칭'('데이터 타입' '매개 변수 이름') {
별칭으로 지정할 코드
}
>>> 반환할 데이터 타입을 지정해주어야 합니다.
void '별칭'('데이터 타입' '매개 변수 이름') {
별칭으로 지정할 코드
}
>>> static을 통해 클래스 이름을 통해 객체를 생성하지 않고도 접근이 가능합니다.
static void '별칭'('데이터 타입' '매개 변수 이름') {
별칭으로 지정할 코드
}
*/
System.out.println("printInfo : " + student.studentName);
}
public static void main(String[] args) {
// Java의 모든 코드는 함수 안에 작성합니다.
/*
- 'Student.java'에서 작성한 Student 클래스를 사용하기
1) 클래스 spec을 만족하는 객체를 생성합니다.
2) 데이터 저장
*/
Student student1 = new Student();
/*
- 복합형 데이터를 다루는 클래스이기 때문에 new 로 객체를 생성합니다.
- 대입 연산자의 왼쪽 부터 실행됩니다.
- Heap 공간에 Student() 메소드의 객체를 생성합니다.
- 클래스의 spec의 조건을 충족시키는지 확인합니다.
- Stack 공간에 Heap 공간의 Student() 메소드의 메모리의 주소를 student 변수에 저장
*/
// 데이터 저장
student1.studentName = "stName1";
student1.address = "Address 123-123";
/*
- 클래스의 spec에 맞는 객체의 정보를 저장합니다.
'클래스 이름'.'멤버 변수 이름' = '저장할 값';
*/
// 데이터 출력
student1.showStudentInfo();
/*
Name : stName1
Address : Address 123-123
- showStudentInfo() 함수를 호출하여 실행합니다.
- 함수를 작성한 페이지에 가지 않는 한 함수의 자세한 내용을 알 수는 없습니다.
*/
System.out.println(student1.studentName);
Student student2 = new Student(); // 새로운 메소드 객체를 생성합니다.
student2.studentName = "stName2";
student2.showStudentInfo();
/*
Name : stName2
Address : null
- student2 객체와 student1 객체는 다른 객체이므로 다른 정보가 출력됩니다.
- student2 객체에 address 정보를 저장하지 않았으므로 null 값이 출력됩니다.
*/
System.out.println();
printInfo(student2);
/*
printInfo : stName1
*/
// 멤버 변수 접근
Student student3 = new Student();
student3.setStudentName("stName3"); // 값을 저장합니다.
System.out.println();
System.out.println("student3.getStudentName() : " + student3.getStudentName());
// 값을 불러옵니다.
System.out.println("student3.studentName : " + student3.studentName);
// 값을 출력합니다.
/*
student3.getStudentName() : stName3
student3.studentName : stName3
*/
// 멤버 변수 접근 제한
/*
student3.grade();
- 오류 : The method grade() is undefined for the type Student
- Student 클래스에서 private으로 선언한 grade의 값에 접근할 수 없습니다.
*/
System.out.println();
System.out.println("student3.getGrade() : " + student3.getGrade());
/*
student3.getGrade() : 0
*/
student3.setGrade(7);
System.out.println();
System.out.println("student3.setGrade(7) : " + student3.getGrade());
/*
student3.setGrade(7) : 7
*/
// 생성자
Student student4 = new Student(1);
student4.setStudentName("stName4");
student4.setGrade(2);
student4.showStudentInfo();
/*
Name : stName4
Address : null
ID : 1
*/
Student student5 = new Student("stName5");
student5.showStudentInfo();
/*
Name : stName5
Address : null
ID : 0
*/
Student student6 = new Student(2,"stName6","Address 456-456",2);
// 변수 선언 순서에 주의해서 작성해야 합니다.
student6.showStudentInfo();
/*
Name : stName6
Address : Address 456-456
ID : 2
*/
}
}
|
- 반복되는 코드 간략하게 작업하기
=====
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
import java.util.*;
public class same {
public static void main(String[] args) {
star();
// star() 메소드 호출
star(5);
// star(a) 메소드 호출
star(3.2);
// star(a) 메소드는 int 형 매개 변수만을 취급하므로 오류 발생
// >> double 형 매개 변수를 가지는 메소드를 선언
star(3, 2);
// 매개 변수가 2개인 star(a, b) 메소드 호출
}
public static void star() {
// 매개 변수가 없고, 반환형도 없는 메소드 선언
System.out.println("**********");
}
public static void star(int a) {
// 매개 변수가 있고, 반환형도 없는 메소드 선언
for (int i = 0; i < a; ++i) {
System.out.print("*");
}
System.out.println();
}
public static void star(double a) {
// 매개 변수가 있고, 반환형도 없는 메소드 선언
for (int i = 0; i < a; ++i) {
System.out.print("*");
}
System.out.println();
}
public static void star(int a, int b) {
// 매개 변수가 2 개이고, 반환형이 없는 메소드 선언
for (int i = 0; i < b; ++i) {
// 1 부터 b 만큼 반복
star(a);
// 매개 변수가 1 개인 메소드 호출
}
}
}
|
- 두 수와 연산자를 입력받아 연산 출력
=====
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
import java.util.*;
public class same {
public static void main(String[] args) {
while(true) {
Scanner in = new Scanner(System.in);
int num1 = input();
int num2 = input();
System.out.print("Choose in [ +, -, *, /, %% , |(cancle)] : ");
String a = in.next();
System.out.printf("%d %s %d = ", num1, a, num2);
switch(a) {
case "+":
System.out.println(plus(num1,num2));
break;
case "-":
System.out.println(minus(num1,num2));
break;
case "*":
System.out.println(multi(num1,num2));
break;
case "/":
System.out.println(div(num1,num2));
break;
case "%":
System.out.println(mod(num1,num2));
break;
case "|":
System.out.println("Finish");
System.exit(0);
default:
System.out.println("Wrong!!");
}
}
}
public static int input() {
Scanner in = new Scanner(System.in);
System.out.print("Input number : ");
int num = in.nextInt();
return num;
}
public static int plus(int a, int b){
return a+b;
}
public static int minus(int a, int b){
return a-b;
}
public static int multi(int a, int b){
return a*b;
}
public static double div(int a, int b){
return a+(float)b;
}
public static int mod(int a, int b){
return a%b;
}
}
|
- 방 배정 프로그램 메소드로 작성
=====
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
import java.util.*;
public class Exam_02 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("방의 갯수를 입력 : ");
int roomSu = in.nextInt();
boolean[] room = new boolean[roomSu];
//false - 빈방, true - 사용중
while (true) {
System.out.print("1.입실 2.퇴실 3.보기 4.종료 : ");
int select = in.nextInt();
int roomNum;
switch (select) {
case 1:
input(room, roomSu);
break;
case 2:
output(room, roomSu);
break;
case 3:
view(room, roomSu);
break;
case 4:
exit();
default:
System.out.println("잘못입력하셨습니다. 다시 입력해 주세요");
}
}
}
public static void input(boolean[] room, int roomSu) {
Scanner in = new Scanner(System.in);
System.out.print("입실하실 방의 번호 : ");
int roomNum = in.nextInt();
if (roomNum < 1 || roomNum > roomSu) {
System.out.printf("%d호실부터 %d호실까지만 입력가능\n", 1, roomSu);
return;
}
if (room[roomNum - 1]) {
//roomNum-1을 한 이유? 배열은 0부터 시작, 사람은 1부터 시작
System.out.println(roomNum + "호실은 사용중 입니다");
}
else {
room[roomNum - 1] = true;
System.out.println(roomNum + "호실에 입실하셨습니다.");
}
}
public static void output(boolean[] room, int roomSu) {
Scanner in = new Scanner(System.in);
System.out.print("퇴실하실 방의 번호 : ");
int roomNum = in.nextInt();
if (roomNum < 1 || roomNum > roomSu) {
System.out.printf("%d호실부터 %d호실까지만 입력가능\n", 1, roomSu);
return;
}
if (!room[roomNum - 1]) {//! : 논리부정연산자
//roomNum-1을 한 이유? 배열은 0부터 시작, 사람은 1부터 시작
System.out.println(roomNum + "호실은 현재 빈방입니다");
}
else {
room[roomNum - 1] = false;
System.out.println(roomNum + "호실에서 퇴실하셨습니다.");
}
}
public static void view(boolean[] room, int roomSu) {
for (int i = 0; i < roomSu; ++i) {
if (room[i]) {
System.out.println(i + 1 + "호실은 사용중");
}
else {
System.out.println(i + 1 + "호실은 빈방");
}
}
}
public static void exit() {
System.out.println("프로그램을 종료합니다.");
System.exit(0); //프로그램 종료시켜라
}
}
|
반응형