throw
=> 인위적 Exception
=> 클래스파일에서 발생 가능한 에러에 미리 대비 => 메인메소드에서 try, catch문으로 실행
- account
int withdraw(int amount) throws Exception {
if (balance<amount) {
throw new Exception("잔액 부족"); //모든 exception 포괄함(원래는 특정 이름 지정해야 함)
}
balance-=amount;
return amount;
}
- account ex1
try {
int amount = gildong.withdraw(70000);
System.out.println("찾은 금액: "+amount);
}catch(Exception e) {
System.out.println(e.getMessage());
}
//
잔액 부족
다른 생성자 호출 (this)
: this() 코드 사용해 생성자에서 다른 생성자 호출 / 자신의 다른 생성자 호출
필드 초기화 내용 => 한 생성자에만 집중 => 중복 코드 예방
생성자의 첫 줄에서만 허용
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
|
public class Car{
//필드
String compnay="현대";
String model;
String color;
int maxSpeed;
//생성자
Car(){}
Car(String model){
this(model, "은색", 250); //호출
}
Car(String model, String color){
this(model, color, 250); //호출
}
Car(String model, String color, int maxSpeed){ //공통 실행 코드
this.model=model;
this.color=color;
this.maxSpeed=maxSpeed;
}
}
|
cs |
메소드 오버로딩
: 클래스 내에 같은 이름의 메소드를 여러 개 선언
1. 매개변수 개수 달라야 함
2. 매개변수 개수 같으면 타입/순서 달라야 함
- PhyisicalInfo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public class PhysicalInfo {
//필드
String name;
int age;
float height, weight;
//생성자
public PhysicalInfo(String name, int age, float height, float weight) {
this.name=name;
this.age=age;
this.height=height;
this.weight=weight;
//매개변수 이름=필드 이름 편리, but 구분 필요 => 필드값에는 this 추가
}
//메서드
void update (int age, float height, float weight) {
this.age=age;
this.height=height;
this.weight=weight;
}
}
|
cs |
※매개변수 이름 바꿧을 때
void update (int a, float b, float c) {
age=a;
height=b;
weight=c;
=>
- 메소드 오버로딩 구현 (PhysicalInfo)
void update (int age, float height) {
this.age=age;
this.height=height;
}
- 메소드 오버로딩 실행 (PhysicalInfo ex1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public static void main(String[] args) {
PhysicalInfo younghee = new PhysicalInfo("이영희", 10, 135.5f, 38.0f);
printPhyiscalInfo(younghee);
younghee.update(11, 145.0f, 44.2f);
printPhyiscalInfo(younghee);
younghee.update(12, 157.9f);
printPhyiscalInfo(younghee);
}//메인
public static void printPhyiscalInfo(PhysicalInfo obj) {
System.out.println("이름 : "+obj.name);
System.out.println("나이 : "+obj.age);
System.out.println("키 : "+obj.height);
System.out.println("몸무게 : "+obj.weight);
System.out.println("---------------------------");
}
|
cs |
//
이름 : 이영희
나이 : 10
키 : 10.0
몸무게 : 38.0
---------------------------
이름 : 이영희
나이 : 11
키 : 145.0
몸무게 : 44.2
---------------------------
이름 : 이영희
나이 : 12
키 : 157.9
몸무게 : 44.2
---------------------------
- 매개변수 없는 메소드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public class Rectangle {
int width;
int height;
public Rectangle(int width, int height) {
this.width=width;
this.height=height;
}
int getArea() {
return width*height;
}
}
|
cs |
1
2
3
4
5
6
7
8
9
10
|
public class RectangleEx1 {
public static void main(String[] args) {
Rectangle rect1 = new Rectangle(20, 30);
int area = rect1.getArea();
System.out.println("사각형 너비 : "+rect1.width );
//객체 생성 -> 필드, 메소드에 접근 가능 System.out.println("사각형 높이 : "+rect1.height );
System.out.println("사각형 면적 : "+area );
}
}
|
cs |
매개변수 수 모를 경우
- 1. 매개변수를 배열타입으로 선언 => 메소드 호출 시 배열 나열
1
2
3
4
5
6
7
8
9
|
public class Calculator {
int sum1(int[] values) {
int sum=0;
for (int i=0;i<values.length;i++) {
sum+=values[i];
}
return sum;
}
}
|
cs |
1
2
3
4
5
6
7
8
9
10
11
|
public class CalculatorEx1 {
public static void main(String[] args) {
Calculator myCalc = new Calculator();
int[] value1 = {10,85,31,64,33};
int result1=myCalc.sum1(value1);
System.out.println("배열의 총합 : "+result1);
int result2 = myCalc.sum1(new int[] {85,90,40});
System.out.println("새 배열의 총합 : "+ result2);
}
}
|
cs |
//
배열의 총합 : 223
새 배열의 총합 : 215
ex2
printAccount(chanho);
printAccount(new Account("1112-222-3333", "dd" , 0));
=> 익명으로 (객체명 지정 없이) 리턴 값 받음
- 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
|
public class Calculator {
//배열을 매개변수로 받아 처리하는 메소드
int sum1(int[] values) {
int sum=0;
for (int i=0;i<values.length;i++) {
sum+=values[i];
}
return sum;
}
//매개변수로 데이터를 받아서 처리하는 메소드
int sum2(int num1, int num2, int num3) {
int sum=0;
sum=num1+num2+num3;
return sum;
}
//매개변수의 수를 모를 경우 처리하는 메소드
int sum3(int ...nums) {
int sum=0;
for (int i=0;i<nums.length;i++) {
sum+=nums[i];
}
return sum;
}
}
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public class CalculatorEx1 {
public static void main(String[] args) {
Calculator myCalc = new Calculator();
int[] value1 = {10,85,31,64,33};
int result1=myCalc.sum1(value1);
System.out.println("배열의 총합 : "+result1);
int result2 = myCalc.sum1(new int[] {85,90,40});
System.out.println("배열의 총합 : "+ result2);
int result3 = myCalc.sum3(20, 80, 60);
System.out.println("자료의 총합 : "+result3);
int result4 = myCalc.sum3(20, 80, 60,85,90);
System.out.println("자료의 총합 : "+result4);
}
}
|
cs |
- 평균 구하기
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
|
public class Calculator {
//배열을 매개변수로 받아 합계 구하는 메소드
int sum1(int[] values) {
int sum=0;
for (int i=0;i<values.length;i++) {
sum+=values[i];
}
return sum;
}
//매개변수의 수 몰라도 합계 구하는 메소드
int sum2(int ...nums) {
int sum=0;
for (int i=0;i<nums.length;i++) {
sum+=nums[i];
}
return sum;
}
//배열을 매개변수로 받아 평균 구하는 메소드
double avg1(int[] values) {
int sum=0;
for (int i=0;i<values.length;i++) {
sum+=values[i];
}
double avg = (double)sum/values.length;
return avg;
}
//매개변수의 수 몰라도 평균 구하는 메소드
double avg2(int ...nums) {
int sum=0;
for (int i=0;i<nums.length;i++) {
sum+=nums[i];
}
double avg = (double)sum/nums.length;
return avg;
}
}
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public class CalculatorEx1 {
public static void main(String[] args) {
Calculator myCalc = new Calculator();
int[] value1 = {10,85,31,64,33};
int result1=myCalc.sum1(value1);
System.out.println("배열의 총합 : "+result1);
int result2 = myCalc.sum1(new int[] {85,90,40});
System.out.println("배열의 총합 : "+ result2);
int result3 = myCalc.sum2(20, 80, 60);
System.out.println("자료의 총합 : "+result3);
int result4 = myCalc.sum2(20, 80, 60,85,90);
System.out.println("자료의 총합 : "+result4);
double result5 = myCalc.avg2(35,46,34,23,12);
System.out.println("자료의 평균 : "+result5);
}
}
|
cs |
- 클래스 내부에서 메소드 호출 => 중복 줄이기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
//배열을 매개변수로 받아 평균 구하는 메소드
double avg1(int[] values) {
int sum = sum1(values);
double avg = (double)sum/values.length;
return avg;
}
//매개변수의 수 몰라도 평균 구하는 메소드
double avg2(int ...nums) {
int sum = sum2(nums);
double avg = (double)sum/nums.length;
return avg;
}
}
|
cs |
캡슐화 (정보 은닉), getter 와 setter
- private 접근제한자 사용
public class Rectangle {
private int width;
private int height;
=> 다른 클래스에서 필드 단독 사용 불가, 에러 발생
- 접근제한자 -> width, height 접근 불가
1
2
3
4
5
6
7
8
9
10
11
|
public class RectangleEx1 {
public static void main(String[] args) {
Rectangle rect1 = new Rectangle(20, 30);
// rect1.width=-10;
int area = rect1.getArea();
// System.out.println("사각형 너비 : "+rect1.width );
//객체 생성 -> 필드, 메소드에 접근 가능 // System.out.println("사각형 높이 : "+rect1.height );
System.out.println("사각형 면적 : "+area );
}
}
|
cs |
=>해결
- getter
: private 필드를 간접적으로 접근 / 값만 가져옴 (source-generate getters and setters)
- getter 사용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class Rectangle {
private int width;
private int height;
public Rectangle(int width, int height) {
this.width=width;
this.height=height;
}
int getArea() {
return width*height;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
}
|
cs |
1
2
3
4
5
6
7
8
9
10
|
public class RectangleEx1 {
public static void main(String[] args) {
Rectangle rect1 = new Rectangle(20, 30);
int area = rect1.getArea();
System.out.println("사각형 너비 : "+rect1.getWidth());
System.out.println("사각형 높이 : "+rect1.getHeight());
System.out.println("사각형 면적 : "+area );
}
}
|
cs |
- + 필드에 음수값, 0 비허용 설정하기
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
|
public class Rectangle {
private int width;
private int height;
public Rectangle(int width, int height) throws Exception {
if (width<=0 || height<=0) {
throw new Exception("너비와 높이는 양수만 가능");
}
this.width=width;
this.height=height;
}
int getArea() {
return width*height;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public int getHeight() {
return height;
}
}
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public class RectangleEx1 {
public static void main(String[] args) {
try {
Rectangle rect1 = new Rectangle(20, 30);
int area = rect1.getArea();
System.out.println("사각형 너비 : "+rect1.getWidth());
System.out.println("사각형 높이 : "+rect1.getHeight() );
System.out.println("사각형 면적 : "+area );
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
|
cs |
=>
throws Exception 설정 => ex 클래스에 오류 대응책으로 try catch문 작성 필수
- setter
: 값 변경 후 출력 (필드가 private 므로 접근 불가, 메소드 이용해 변경)
- rectangle
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
|
public class Rectangle {
private int width;
private int height;
public Rectangle(int width, int height) throws Exception {
if (width<=0 || height<=0) {
throw new Exception("너비와 높이는 양수만 가능");
}
this.width=width;
this.height=height;
}
int getArea() {
return width*height;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
}
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public class RectangleEx1 {
public static void main(String[] args) {
try {
Rectangle rect1 = new Rectangle(20, 30);
int area = rect1.getArea();
System.out.println("사각형 너비 : "+rect1.getWidth());
System.out.println("사각형 높이 : "+rect1.getHeight() );
System.out.println("사각형 면적 : "+area );
rect1.setWidth(50);
rect1.setHeight(70);
area=rect1.getArea();
System.out.println("사각형 너비 : "+rect1.getWidth());
System.out.println("사각형 높이 : "+rect1.getHeight() );
System.out.println("사각형 면적 : "+area );
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
|
cs |
- setter 음수, 0 비허용 설정
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
|
public class Rectangle {
private int width;
private int height;
public Rectangle(int width, int height) throws Exception {
if (width<=0 || height<=0) {
throw new Exception("너비와 높이는 양수만 가능");
}
this.width=width;
this.height=height;
}
int getArea() {
return width*height;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public void setWidth(int width) throws Exception {
if(width<=0) {
throw new Exception("너비는 양수만 가능");
}
this.width = width;
}
public void setHeight(int height) throws Exception{
if(height<=0) {
throw new Exception("높이는 양수만 가능");
}
this.height = height;
}
}
|
cs |
static final (상수 필드)
=> 필드 이름 전체 대문자
=> 객체 생성되지 않아도 원본클래스 자체에서 접근 가능
cf. 인스턴트 필드
=> new 명령문으로 값 계속 바뀜
=> 객체 생성해야지 실행 가능
- account
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
|
public class Account {
//상수 필드
static final String BANKNAME = "신한은행";
//인스턴트 필드 : 변수
String accountNo;
String ownerName;
int balance;
public Account(String accountNo, String ownerName, int balance) {
this.accountNo=accountNo; //this=> 필드
this.ownerName=ownerName;
this.balance=balance;
}
public Account() {
}
void deposit (int amount) { //void : 리턴값 없음 //괄호 안: 매개변수 ex.주스받을 컵
balance+=amount;
}
int withdraw(int amount) throws Exception { //리턴값(돌아오는 결과) : int
if (balance<amount) {
throw new Exception("잔액 부족");
}
balance-=amount;
return amount;
}
}
|
cs |
1
2
3
4
5
6
7
|
public class AccountEx2 {
public static void main(String[] args) { //main : 메소드의 이름임
Account younghee = new Account("222-222-222","이영희",100);
System.out.println(Account.BANKNAME); //객체 없이 클래스로만 접근
~
|
cs |
정적 필드, 메소드 (static)
정적 블록 안에서는
=> 인스턴스 필드, 메소드 사용 불가
=> this 사용불가
싱글톤
: 클래스 외부에서 new 연산자로 생성자 호출할 수 없도록 막아 만들어지는 단 하나의 객체
생성자 앞에 private 제한자 붙임
정적 필드, 정적 메소드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public class Cheomseongdae {
//정적 필드
private static Cheomseongdae cheom = new Cheomseongdae(); //클래스 자체가 필드가 됨
//private 생성자
private Cheomseongdae() {
}
//정적 메서드
static Cheomseongdae getInstance() { //Cheomseongdae: 타입 이름 / getInstance: 메소드 이름
return cheom;
}
void history() {
System.out.println("경주");
}
}
|
cs |
- ex1
1
2
3
4
5
6
7
8
|
public class CheomseongdaeEx1 {
public static void main(String[] args) {
}
}
|
cs |
=> 싱글톤이므로 새 객체 생성 불가
- 외부에서 객체 얻는 법 - getinstance 메소드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public class CheomseongdaeEx1 {
public static void main(String[] args) {
Cheomseongdae cheom1 = Cheomseongdae.getInstance();
Cheomseongdae cheom2 = Cheomseongdae.getInstance();
if (cheom1==cheom2) {
System.out.println("같은 첨성대 객체");
}else {
System.out.println("다른 첨성대 객체");
}
cheom1.history();
cheom2.history();
}
}
|
cs |
//
같은 첨성대 객체
경주
경주
=> 하나의 객체(싱글톤) 가리킴
import 문
같은 패키지 => 조건 없이 다른 클래스 사용 가능
다른 패키지 => import 패키지.클래스명;
접근제한자
접근제한 | 적용 대상 | 접근 가능/불가 클래스 |
public | 클래스, 필드, 생성자, 메소드 | 모두 접근 가능 |
protected | 필드, 생성자, 메소드 | 같은 패키지 / 자식클래스만 접근 가능 |
default | 클래스, 필드, 생성자, 메소드 | 같은 패키지만 접근 가능 |
private | 필드, 생성자, 메소드 | 모든 외부 클래스 접근 불가 |
기타
void 메소드 : 코드 실행만 하고 결과 리턴하지 않음
데이터타입(int,...) 메소드 : 해당 타입의 리턴값 있는 메소드
- 필드 => 객체 생성 시 자동으로 기본 초기값 설정됨
기본타입(byte, char, float) : 0
boolean : false
참조타입(배열, 클래스, String, 인터페이스) : null
- 클래스 생성시 생성자 없으면 디폴트 생성자 생성됨 (= 생성자 필수)
////
매개변수는 없고 리턴값만 있는 메소드 => 더 찾아볼 것
싱글톤 => 정적 필드에서 클래스 자체가 필드 된다는 것 헷갈림
ㅎㅎㅎㅎ영어도 문법 나름 좋아했어서 그런가 아직은 자바 문법 재밌다 ㅎ 복습하니까 확실히 제대로 이해되는 느낌
'Programming > 국비학원' 카테고리의 다른 글
220504 - 어노테이션, 다형성(클래스, 메소드, 매개변수), 추상클래스, 7장 상속 확인문제 (0) | 2022.05.05 |
---|---|
220503 - 6장 클래스 확인문제, 상속(extends), 오버라이딩(재정의) (0) | 2022.05.04 |
220429 - final, 6장 클래스, exception / 5장 참조 문풀 (0) | 2022.04.30 |
220428 - 배열 복사, 열거 타입 (0) | 2022.04.29 |
220429 - 버전 관리 - CLI, GUI (0) | 2022.04.29 |