p403 - 424
내부 클래스
p403
1.
ㅡㅡㅡㅡㅡㅡ 인스턴스 멤버 ㅡㅡㅡㅡㅡㅡ
10
Inner: print() Call: name = 김가가
ㅡㅡㅡㅡㅡㅡ static 멤버 ㅡㅡㅡㅡㅡㅡ
Inner:print() Call...
ㅡㅡㅡㅡㅡㅡ 지역 클래스 ㅡㅡㅡㅡㅡㅡ
지역 클래스: Inner: print() Call...
ㅡㅡㅡㅡㅡㅡ 익명의 클래스 ㅡㅡㅡㅡㅡㅡ
Inner4: print() Call...
Outer4에서 print() 오버라이딩...
class Outer
{
private String name = "김가가";
class Inner
{
int a = 10;
public void print()
{
System.out.println("Inner: print() Call: name = " + name);
}
}
}
// static 사용 시
class Outer2
{
static class Inner
{
public void print()
{
System.out.println("Inner:print() Call...");
}
}
}
// 지역 클래스 사용 시
class Outer3
{
public void print()
{
class Inner
{
public void print()
{
System.out.println("지역 클래스: Inner: print() Call...");
}
}
Inner i = new Inner();
i.print();
}
}
// 익명의 클래스 사용 시
class Outer4
{
Inner4 in = new Inner4()
{
public void print()
{
System.out.println("Outer4에서 print() 오버라이딩...");
}
};
}
class Inner4
{
public void print()
{
System.out.println("Inner4: print() Call...");
}
}
public class MainClass {
public static void main(String[] args) {
// 인스턴스 멤버 사용 시
System.out.println("ㅡㅡㅡㅡㅡㅡ 인스턴스 멤버 ㅡㅡㅡㅡㅡㅡ");
Outer p = new Outer();
Outer.Inner c = p.new Inner();
System.out.println(c.a);
c.print();
System.out.println("ㅡㅡㅡㅡㅡㅡ static 멤버 ㅡㅡㅡㅡㅡㅡ");
// static 사용 시
Outer2.Inner c1 = new Outer2.Inner();
c1.print();
// 지역 클래스 사용 시
System.out.println("ㅡㅡㅡㅡㅡㅡ 지역 클래스 ㅡㅡㅡㅡㅡㅡ");
Outer3 o = new Outer3();
o.print();
System.out.println("ㅡㅡㅡㅡㅡㅡ 익명의 클래스 ㅡㅡㅡㅡㅡㅡ");
Inner4 i1 = new Inner4();
i1.print();
Outer4 i2 = new Outer4();
i2.in.print();
}
}
각 클래스 종류 사용 예시 알자
2. 학생 성적표
package com.sist.main;
import javax.swing.*;
import javax.swing.table.*;
public class StudentMain extends JFrame {
JTable table;
DefaultTableModel model;
public StudentMain()
{
String[] col = {"학번", "이름", "국어", "영어", "수학"};
String[][] row = new String[0][5]; // 한 컬럼당 5개 출력
// 내용 수정
model = new DefaultTableModel(row, col)
{
// 수정 할 수 없게 함
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
table = new JTable(model);
JScrollPane js = new JScrollPane(table);
add("Center", js);
setSize(640, 480);
String[] data = {"1", "김가가", "90", "80", "90"};
model.addRow(data);
setVisible(true);
}
public static void main(String[] args) {
new StudentMain();
}
}
3. 변수 우선순위
value = 30
value = 20
value = 10
class Outer5
{
int value = 10;
class Inner
{
int value = 20;
public void method()
{
int value = 30;
System.out.println("value = " + value);
// 지역변수 우선순위라서 → 30
System.out.println("value = " + this.value); // 20
System.out.println("value = " + Outer5.this.value); // 10
}
}
}
public class MainClass2 {
public static void main(String[] args) {
Outer5 o = new Outer5();
Outer5.Inner i = o.new Inner();
i.method();
}
}
// 간단 구현
public void display()
{
Inner i = new Inner();
i.method();
}
o.display();
예외 처리
p414
try
{
정상 명령문
-정상
-정상
-에러 → catch로 이동 → 건너뛴다
-정상
} catch(발생할 예외처리 클래스 1){에러처리문장}
catch(발생할 예외처리 클래스 2){에러처리문장}
catch(발생할 예외처리 클래스 3){에러처리문장}
catch(발생할 예외처리 클래스 4){에러처리문장}
catch(발생할 예외처리 클래스 5){에러처리문장}
finally → 필요 시에만 사용
{
무조건 수행하는 문장 (오라클, 서버, 파일에 사용) → 반드시 닫는다
}
예외처리 종류
public static void main(String[] args) {
try
{
}
catch(ArrayIndexOutOfBoundsException ex)
{
System.out.println("배열 범위 초과");
}
catch(ArithmeticException ex)
{
System.out.println("0으로 나눌 수 없음");
}
catch(NumberFormatException ex)
{
System.out.println("정수형 변환 안됨");
}
catch(ClassCastException ex)
{
System.out.println("클래스 객체의 값이 없음");
}
catch(NullPointerException ex)
{
System.out.println("예외의 모든 에러는 잡을 수 있음");
}
catch(Exception ex) // 기타
{
}
System.out.println("프로그램 종료!!"); // 출력 되어야지만 정상 종료
}
예제
1.
10
public static void main(String[] args) {
String s = " 10"; // 공백 때문에 에러
// 예외 처리로 정상 출력 시킨다
try {
int a = Integer.parseInt(s);
} catch(Exception e) {}
System.out.println(s);
}
2.
i = 1,1
i = 2,1
에러 발생
i = 4,2
i = 5,2
에러 발생
i = 7,7
i = 8,4
에러 발생
에러 발생
public static void main(String[] args) {
for(int i=1; i<=10; i++)
{
try
{
int a = (int)(Math.random()*3);
System.out.println("i = " + i + "," + i/a);
} catch(Exception ex) { System.out.println("에러 발생"); }
}
}
3.
1
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.sist.exception.MainClass.main(MainClass.java:8)
public static void main(String[] args) {
System.out.println("1");
System.out.println(10/0); // try-catch 전 에러
try
{
System.out.println("3");
System.out.println(10/0); // 에러 → 빠짐
System.out.println("5");
} catch(Exception ex)
{
System.out.println("6"); // catch 값 빠짐
}
// 무조건 수행
finally
{
System.out.println("7");
}
System.out.println("8");
System.out.println("9");
}
1
2
3
6
7
8
9
public static void main(String[] args) {
System.out.println("1");
System.out.println("2");
try
{
System.out.println("3");
System.out.println(10/0); // 에러 → 빠짐
System.out.println("5");
} catch(Exception ex)
{
System.out.println("6"); // catch 값 빠짐
}
// 무조건 수행
finally
{
System.out.println("7");
}
System.out.println("8");
System.out.println("9");
}
4.
에러 발생!!
수행 완료!!
public static void main(String[] args) {
try
{
int a = 10/0;
}
catch(ArrayIndexOutOfBoundsException | ArithmeticException e)
{
System.out.println("에러 발생!!");
}
System.out.println("수행 완료!!");
}
5. 에러 메세지 처리
getMessage() 실제 에러 내용만 출력
printStackTrace() 에러 위치 확인 (**)
// getMessage()
첫번째 정수:
10
두번째 정수:
0
/ by zero
//printStackTrace()
첫번째 정수:
10
두번째 정수:
0
java.lang.ArithmeticException: / by zero
at com.sist.exception.MainClass.main(MainClass.java:23) // 에러 위치
public static void main(String[] args) {
try
{
Scanner sc = new Scanner(System.in);
System.out.println("첫번째 정수: ");
int num1 = sc.nextInt();
System.out.println("두번째 정수: ");
int num2 = sc.nextInt();
int[] arr = new int[2];
arr[0] = num1;
arr[1] = num2;
int result = num1/num2;
System.out.println(result);
}
catch(Exception ex)
{
// System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
예외 처리 응용
1. 채팅 프로그램
Server Start...
64648
127.0.0.1
server
import java.net.*;
import java.util.*;
import java.io.*;
public class Server implements Runnable {
private ServerSocket ss;
private final int PORT = 3355;
private Vector<Client> waitVc = new Vector<Client>(); // 접속자 정보 저장 → IP
// 서버 → 접속 담당
public Server()
{
try
{
ss = new ServerSocket(PORT);
System.out.println("Server Start...");
}
catch(Exception ex){}
}
@Override
public void run()
{
while(true)
{
try
{
Socket s = ss.accept();
Client client = new Client(s);
// 접속자 IP 읽어오기
System.out.println(s.getPort());
System.out.println(s.getInetAddress().getHostAddress());
waitVc.add(client); // 접속자 추가
client.start(); // 통신 시작
} catch(Exception ex) {}
}
}
public static void main(String[] args) {
Server server = new Server();
new Thread(server).start();
}
// 통신 담당
class Client extends Thread
{
Socket s;
OutputStream out;
BufferedReader in;
public Client(Socket s)
{
try
{
// 전화기
this.s = s;
// 전화선
out = s.getOutputStream();
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
} catch(Exception ex) {}
}
public void run()
{
while(true)
{
try
{
String msg = in.readLine();
for(Client c:waitVc)
{
c.out.write((msg + "\n").getBytes());
}
} catch(Exception ex) {}
}
}
}
}
client
import java.net.*;
public class Client {
public static void main(String[] args) {
try
{
Socket s = new Socket("localhost", 3355);
} catch(Exception ex) {}
}
}
'수업' 카테고리의 다른 글
+24 라이브러리 (0) | 2022.06.07 |
---|---|
+24 예외처리(throw, throws, finally) (0) | 2022.06.07 |
+22 super, this, 형변환, 추상클래스, 인터페이스 (0) | 2022.06.02 |
+20 캡슐화, 패키지 (0) | 2022.05.30 |
+19 리뷰 프로그램(등록, 보기, 수정, 삭제) (0) | 2022.05.27 |