첫 번째 자바 프로그램
/*
* Main.java
*/
package javaapplication1;
/**
*
* @author Administrator1
*/
public class Main {
/** 생성자 */
public Main() {
}
/**
* 메서드 정의
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Hello World!");
}
}
자료의 표현
public class Data01 {
public static void main(String[] args) {
//(1) 정수 : 소수점이 없는 수
System.out.println(1);
//(2) 실수 : 소수점이 있는 수
System.out.println(1.5);
//(3) 문자 : 단일 따옴표로 묶어줌
System.out.println('a');
//(4) 논리값 : true, false
System.out.println(true);
//(1) long 형 상수 : 숫자 끝에 L 혹은 l을 붙임
System.out.println(1L);
//(2) float 형 상수 : 숫자 끝에 F 혹은 f룰 붙임
System.out.println(1.5f);
//(3) 문자열 : 이중 따옴표로 묶어줌
System.out.println("abc");
}
}
변수 선언
/*
* Data03.java
*/
package section02;
public class Data03 {
public Data03() {
}
public static void main(String[] args) {
int a;//변수 선언하고
a=1;
System.out.println(a);
a=2;
System.out.println(a);
}
}
자료형 변환 및 문자열 처리
public class Data05 {
public static void main(String[] args) {
byte a=1;
short b=128;
int c=32768;
b=a;
//암시적인 형 변환
System.out.println(b);
b=(short)c;
// 명시적인 형변환
//오버플로우가 발생되어 엉뚱한 값 출력
System.out.println(b);
public class Data07 {
public static void main(String[] args) {
char x;
x='A';
System.out.printf(" %c -> %d \n", x, (int)x);
x='0';
System.out.printf(" %c -> %d \n", x, (int)x);
x=0;
//0은 NULL 문자를 의미
System.out.printf(" %c -> %d \n", x, (int)x);
x='a';
System.out.printf(" %c -> %d \n", x, (int)x);
}
}
}
}
public class Data06 {
public static void main(String[] args) {
double a=23.7;
float b=23.7f;
System.out.println(a);
System.out.println(b);
}
}
public class Data08 {
public static void main(String[] args) {
String y;
y="AB";
System.out.println(y);
y="A";
System.out.println(y);
}
}
연산자 – 산술 연산자
class Opr01 {
public static void main(String[] args) {
int a=10, b=4, c;
c=a+b;
System.out.println(a + " + " + b + " = " + c);
c=a-b;
System.out.println(a + " - " + b + " = " + c);
c=a*b;
System.out.println(a + " * " + b + " = " + c);
c=a/b;
System.out.println(a + " / " + b + " = " + c);
c=a%b;
System.out.println(a + " % " + b + " = " + c);
}
}
public class Opr01_02 {
public static void main(String[] args) {
String a="Apple";
String b="Banana";
String c=a+b;
System.out.println(c);
String str="결과값 : ";
int n=10;
System.out.println(str+n);
System.out.println("결과값 : "+n);
}
}
연산자 – 관계, 조건 선택, 대입 연산자
public class Opr02 {
public static void main(String[] args) {
int a=10, b=4, c;
boolean test;
test=a>b;
System.out.println(a + " > " + b + " = " + test);
test=a<b;
System.out.println(a + " < " + b + " = " + test);
System.out.println(a+b > a-b);
}
}
public class Opr03 {
public static void main(String[] args) {
int a=5, b=10;
int max; //최대값을 저장할 변수 선언
max = a>b ? a : b;
System.out.println(" max = "+ max);
}
}
class Opr04 //대입 연산자와 증감 연산자
{
public static void main(String[] args)
{
int a=29;
String s="몰라";
s = (a>=10 && a <=19) ? "10대" : "10대 아님";
System.out.println(a + " => " + s);
}
}
연산자 – 증감 연산자
class Opr07
{
public static void main(String[] args)
{
int a=10, b=10;
++a;
//선행처리
System.out.println(a);
b++;
//후행처리
System.out.println(b);
}
}
class Opr08 //대입 연산자와 증감 연산자
{
public static void main(String[] args)
{
int a=10, b=10;
System.out.println(++a);
System.out.println(a);
System.out.println(b++);
System.out.println(b);
a=b=10;
int c;
c=++a;
System.out.println(c + " => " + a);
c=b++;
System.out.println(c + " => " + b);
}
}
연산자 – 비트 연산자
class Opr09 //비트 단위 논리 연산자
{
public static void main(String[] args)
{
int a=12;
int b=20;
int c;
c = a & b; //비트 단위 값이 둘 다 1일 때만 1
System.out.println(a + " & " + b + " -> " + c);
class Opr10 {
public static void main(String[] args) {
byte x = 15;
System.out.println("x << 2 : " + (x << 2) );
System.out.println("x >> 2 : " + (x >> 2) );
}
}
c = a | b; //비트 단위 값이 둘 다 0일대만 0
System.out.println(a + " | " + b + " -> " + c);
c = a ^ b; //비트 단위 값이 두 값이 다르면 1 같으면 0
System.out.println(a + " ^ " + b + " -> " + c);
c = ~a; //비트 단위 값이 1이면 0으로 0이면 1로
System.out.println("~" + a + " -> " + c);
}
}
제어문 - if
class If01 {
public static void main(String[] args) {
int num;
num = -5;
if(num < 0)
num = -num;
System.out.println(" absolute num = "+ num);
num = 5;
if(num < 0)
num = -num;
System.out.println(" absolute num = "+ num);
}
}
class If02 {
public static void main(String[] args) {
int num=Integer.parseInt(args[0]);//num=40;
if(num%2==1)
System.out.println(num + "는 홀수입니다.");
else
System.out.println(num + "는 짝수입니다.");
}
}
제어문 - if
class If03 {
public static void main(String[] args) {
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int max, min;
if(a > b){
max=a;
min=b;
}
else{
max=b;
min=a;
}
System.out.println("최대 값은 " + max + "입니다.");
System.out.println("최소 값은 " + min + "입니다.");
}
class If04 {
}
public static void main(String[] args) {
int a=Integer.parseInt(args[0]);
if(a>0)
//a가 0보다 크면
System.out.println(a+"는 양수입니다.");
else if(a<0) //a가 0보다 작으면
System.out.println(a+"는 음수입니다.");
else
//a가 0보다 크지도 작지도 않으면
System.out.println("0 입니다.");
}
}
제어문 – switch case
class Switch01{
public static void main(String[] args){
int a = Integer.parseInt(args[0]);
System.out.println(" => " + a);
switch(a){
case 9: System.out.println( " A ");
case 8: System.out.println( " B ");
case 7: System.out.println( " C ");
case 6: System.out.println( " D ");
default : System.out.println( " F ");
}
}
}
class Switch04 {
public static void main(String[] args) {
String str = args[0];
char ch;
ch=str.charAt(0); //='b';
switch(ch) {
case 'A' :
case 'a' : System.out.println("America"); break;
case 'B' :
case 'b' : System.out.println("Britain"); break;
case 'C' :
case 'c' : System.out.println("Canada"); break;
case 'J' :
case 'j' : System.out.println("Japan"); break;
case 'K' :
case 'k' : System.out.println("Korea"); break;
}
}
반복문 - for
class For01
{
public static void main(String[] args)
{
int i;
for(i=1; i<=10; i++)
System.out.println("Hello World!");
}
}
class For02{
public static void main(String[] args) {
int i;
for(i=1; i<=4; i++)
System.out.println(i );
class For04 {
public static void main(String[] args) {
int i; //제어변수 선언
int a=2; //출력할 단을 저장하는 변수 선언, 2단 출력
System.out.println("<<-----" + a + "단----->> " );
for(i=1; i<=9; i++)
System.out.println(a + " * " + i + " = " + (a * i) );
}
}
class For06{
public static void main(String[] args) {
int i;
int total = 0;
for(i=1; i<=5; i++)
total +=i;
System.out.println("1 ~ " + (i-1) + " = " + total);
System.out.println("--->> " + i );
}
}
}
}
반복문 - while
class While01
{
public static void main(String[] args)
{
int i;
for(i=1; i<=5; i++)
System.out.print(" " +i);
System.out.println("\n-------------------------");
i=1;
//초기식
while(i<=5){ //조건식
System.out.print(" " +i); //반복 처리할 문장
i++;
//증감식
}
}
}
제어문 - while
class While03{
public static void main(String[] args) {
int i=0;
while(i++<=4)
System.out.print( i + ", " );
System.out.println("\n--------------------- >>" );
i=1;
do
System.out.print( i + ", " );
while(i++<=4); //do while 문은 반드시 세미콜론으로 끝난다.
System.out.println("\n--------------------- >>" );
i=0;
while(i++<=4) ; //NULL 문으로 인식함
System.out.print( i + ", " );
System.out.println("\n--------------------- >>" );
for(i=1; i<=4; i++) ; //NULL 문으로 인식함
System.out.print( i + ", " );
System.out.println("\n-------------------------");
}
}
For 활용
class E01 {
public static void main(String[] args) {
int n;
//제어변수 선언
int odd_tot, even_tot;
//홀수의 합과 짝수의 합을
누적할 변수
for(odd_tot=0 , n=1; n<=10; n+=2) //홀수를 구함
odd_tot += n;
//구해진 홀수를 누적
for(even_tot=0 , n=2; n<=10; n+=2) //짝수를 구함
even_tot += n;
//구해진 짝수를 누적
System.out.println(" odd_tot(1+3+5+7+9) = " + odd_tot);
//홀수의 합을 출력
System.out.println(" even_tot(2+4+6+8+10) = " +
even_tot); //짝수의 합을 출력
}
}
For, if 활용
class E01_01 {
public static void main(String[] args) {
int n;
//제어변수 선언
int odd_tot, even_tot;
//홀수의 합과 짝수의 합을 누적할 변수
for(odd_tot=0, even_tot=0 , n=1; n<=10; n++) //제어변수 n은 1부터 10사이의 자연수
if(n%2==1)
//n을 2로 나누어서 나머지가 1이면 홀수이므로
odd_tot += n;
//홀수의 합을 누적하는 변수에 더하고
else
//n을 2로 나누어서 나머지가 1이 아니고 0이면 짝수이므로
even_tot += n;
//짝수의 합을 누적하는 변수에 더한다.
System.out.println(" odd_tot(1+3+5+7+9) = " + odd_tot); //홀수의 합을 출력
System.out.println(" even_tot(2+4+6+8+10) = " + even_tot); //짝수의 합을 출력
}
}
다중 for 활용
public class E04 {
public static void main(String[] args) {
int a;
//바깥쪽 for문의 제어변수 선언
int b;
//안쪽 for문의 제어변수 선언
for(a=1; a<=5; a++){
//5줄 반복한다.
for(b=1; b<=5; b++){ //한 줄에 스타(*)를 5번 출력하기 위한 반복문
System.out.print("* "); //안쪽 for문에 의해 반복되는 문장
} //안쪽 for문의 끝
System.out.println();
//줄 바꾸기 위한 문장
}//바깥쪽 for문의 끝
}//main 함수의 끝
}
public class E05 {
public static void main(String[] args) {
int line;
//라인수를 결정하는 변수
int spc;
//공백을 몇 번 출력할지 결정하는 변수
int n;
//숫자를 몇 번 출력할지 결정하는 변수
int number=1;
//출력할 숫자를 저장하는 변수
int size=3;
for(line=1; line<=size ; line++){
//3줄로 출력
for(spc=size-line; spc>=1 ;spc--) //공백 출력할 횟수를 결정
System.out.print(" ");
//공백 출력
for(n=1; n<= line*2-1; n++)
//숫자 출력할 횟수를 결정
System.out.print(number++);
//숫자 출력
System.out.println("");
//줄바꿈
}
}//main 함수의 끝
}
보조 제어문 - break
class F01 {
public static void main(String[] args) {
int n;
for(n=1; n<=10; n++)
System.out.print(" " + n);
System.out.println("");
for(n=1; n<=10; n++){
if(n%3==0)
break;
System.out.print(" " + n);
}
System.out.println("");
}//main 함수의 끝
}
class F01 {
public static void main(String[] args) {
int n, a;
for(n=1; n<=10; n++)
System.out.print(" " + n);
System.out.println("");
exit_for:
for(n=1; n<=10; n++){
System.out.println("");
for( a = 1 ; a <= 10; a++ ) {
if(a%3==0)
break exit_for;
System.out.print(" " + a);
}
}
System.out.println("");
}
}
보조 제어문 - continue
class F02 {
public static void main(String[] args) {
int n;
for(n=1; n<=10; n++){
if(n%3==0)
continue;
System.out.print(" " + n);
}
System.out.println("");
}//main 함수의 끝
}
배열 – 1차원 배열
public class G01 {
public static void main(String[] args) {
int []score = new int [5];
score[0]=95;
score[1]=70;
score[2]=80;
score[3]=75;
score[4]=100;
//반복문으로 배열을 일괄 처리함
for(int i=0; i<5; i++)
System.out.println( (i+1) + " th score[ " + i + " ]
= " + score[i]);
}
}
public class Arr01 {
public static void main(String[] args) {
int []score = {95, 70, 80, 75, 100};
int total=0;
double ave;
//반복문으로 배열을 일괄 처리함
for(int i=0; i<5; i++)
total += score[ i ]; //총합을 구함
ave = (double) total / 5.0; //평균을 구함
System.out.println(" Total = " + total);
System.out.println(" Ave = " + ave);
}
}
배열 – 다차원 배열
public class Arr03 {
public static void main(String[] args)
int [][]score=new int [5][3];
int row, col;
score[0][0]=10; score[0][1]=90;
score[1][0]=60; score[1][1]=80;
score[2][0]=55; score[2][1]=60;
score[3][0]=90; score[3][1]=75;
score[4][0]=60; score[4][1]=30;
{
score[0][2]=70;
score[1][2]=65;
score[2][2]=85;
score[3][2]=95;
score[4][2]=80;
///반복문으로 일괄처리
for(row = 0; row < 5 ; row++){
for(col = 0; col < 3 ; col++)
System.out.print(" " +score[row][col]);
System.out.println(""); //행단위로 줄 바꿈
}
}
}
배열 – 다차원 배열 2
public class Arr04 {
public static void main(String[] args) {
int [][]score = { { 85, 60, 70}, //0 행
{ 90, 95, 80}, //1 행
{ 75, 80, 100}, //2 행
{ 80, 70, 95}, //3 행
{100, 65, 80}
//4 행
};
int [] subject = new int[3]; //각 과목별 총점을 저장할 변수 선언
int [] student = new int[5]; //각 학생별 총점을 저장할 변수 선언
int r, c;
System.out.println("각 과목별 총점구하기 ");
for(c = 0; c < 3 ; c++){
for(r = 0; r < 5 ; r++){
//행을 증가해 가면서
subject[c] += score[r][c]; //각 과목별 총점을 구한다.
}
System.out.println(subject[c]); //각 과목별 총점 출력하기
}
System.out.println("학생별 총점구하기");
for(r = 0; r < 5 ; r++){
//행은 각 학생을 구분하고 해당 학생에 대해서
for(c = 0; c < 3 ; c++){
//열을 증가해 가면서
student[r] += score[r][c]; //국어, 영어, 수학 점수를 합하여 학생별 총점을 구한다.
}
System.out.println(student[r]); //학생별 총점 출력하기
}
}
}
메서드 – 사용자 정의 메서드
public class MethodEx01 {
static void hello_func(){
System.out.println("Hello World!");
}
public static void main(String[] args) {
hello_func();
}
}
public class MethodEx02 {
static void sum(int n)
{
int i;
int tot=0;
for(i=1; i<=n; i++)
tot += i;
System.out.println("1 ~ "+ n + " = " + tot);
}
public static void main(String[] args) {
sum(5);
sum(10);
}
}
메서드 – 사용자 정의 메서드 2
public class MethodEx03 {
//정수값을 하나 전달받음
static int abs(int data)
{
if(data<0)
//전달받은 정수값이 음수라면
data = -data; //-연산자를 이용하여 양수로 변경
return data;
//결과값을 되돌립니다.
}
public static void main(String[] args) {
int num=Integer.parseInt(args[0]);
System.out.println(" absolute data => "+abs(num));
}
}
클래스의 선언 및 활용
public class AnimalTest01 {
public static void main(String[] args) {
Animal a1;
//레퍼런스 변수 선언
a1=new Animal(); //객체 생성
a1.name="원숭이"; //생성된 객체의 멤버에 접근해서 값 대입
a1.age=26;
System.out.print(a1.name); //객체의 멤버에 저장된 값 출력
System.out.print(","+a1.age);
}
}
//이름과 나이를 속성으로 갖는 클래스 설계
class Animal {
/** 속성 선언 */
String name; //이름 속성
int age;
//나이 속성
}
클래스의 선언 및 활용 – 접근 지정자
public class AnimalTest02 {
public static void main(String[] args) {
Animal a1;
a1=new Animal();
a1.name="원숭이";
a1.age=26;
//private 멤버임으 접근 불가능
System.out.print(a1.name);
System.out.print(","+a1.age); //private 멤버이므로 접근 불가능
}
}
class Animal {
String name;
private int age;
}
클래스의 선언과 활용 – 접근 지정자 활용
class Animal {
String name;
private int age;
public void setAge(int new_age){
age=new_age;
}
public int getAge(){
return age;
}
}
public class AnimalTest03 {
public static void main(String[] args) {
Animal a1;
a1=new Animal();
a1.name="원숭이";
//a.age=26;
//public이어야만 허용된다.
a.setAge(26);
System.out.println(a.name);
//System.out.println(","+a.age); //public이어야만 허용된다.
System.out.println("," + a.getAge( ) );
}
}
클래스의 메서드 - 다형성
public class MethodTest01{
public static void main(String[] args) {
//(1) 논리값 : true, false
System.out.println(true);
//(2) 문자 : 단일 따옴표로 묶어줌
System.out.println('A');
//(3) 정수 : 소수점이 없는 수
System.out.println(128);
//(4) 실수 : 소수점이 있는 수
System.out.println(3.5);
//(5) 문자열 : 이중 따옴표로 묶어줌
System.out.println("Hello");
}
}
클래스의 메서드 – 다형성 2
public class MethodTest02{
int abs(int num){
if(num<0)
num=-num;
return num;
}
long abs(long num){
if(num<0)
num=-num;
return num;
}
double abs(double num){
if(num<0)
num=-num;
return num;
}
public static void main(String[] args) {
MethodTest02 mt=new MethodTest02();
int var01=-10, var02;
var02=mt.abs(var01);
System.out.println(var01 + "의 절대값은-> " + var02);
long var03=-20L, var04;
var04=mt.abs(var03);
System.out.println(var03 + "의 절대값은-> " + var04);
double var05=-3.4, var06;
var06=mt.abs(var05);
System.out.println(var05 + "의 절대값은-> " + var06);
}
}
클래스의 메서드 – 다형성 3
public class MethodTest03{
//정수형 데이터 3개를 형식매개변수로 갖는 prn 메소드 정의
void prn(int a, int b, int c) {
System.out.println(a +"\t" + b +""\t" +c);
}
//정수형 데이터 2개를 형식매개변수로 갖는 prn 메소드 정의
void prn(int a, int b) {
System.out.println(a +""\t" + b);
}
//정수형 데이터 1개를 형식매개변수로 갖는 prn 메소드 정의
void prn(int a){
System.out.println(a);
}
public static void main(String[] args){
MethodTest03 mt=new MethodTest03();
mt.prn(10, 20, 30); //정수형 데이터 3개를 실매개변수로 지정
mt.prn(40, 50);
//정수형 데이터 2개를 실매개변수로 지정
mt.prn(60);
//정수형 데이터 1개를 실매개변수로 지정
}
}
클래스의 메서드 – 다형성 4
class MethodTestA{
void prn(int a){
System.out.println(a);
}
int prn(int a){
return a;
}
public static void main(String[] args){
MethodTest03 mt=new MethodTest03();
mt.prn(10);
//정수형 데이터 1개를 실매개변수로 지정
int k;
k=mt.prn(10);
}
}
클래스의 메서드 - varargs
public class MethodTest04{
void prn(int ... num){
//int형 데이터를 출력하는 메소드의 정
의
for(int i=0; i<num.length; i++) //전달인자의 개수만큼 반복하면
서
System.out.print(num[i]+"\t"); //배열 형태로 출력한다.
System.out.println();
}
public static void main(String[] args)
{
MethodTest04 mt=new MethodTest04();
mt.prn(10, 20, 30); //개수에 상관없이 메소드를 호출할 수 있다.
mt.prn(40, 50);
mt.prn(60);
}
}
클래스 – 기본 자료형과 레퍼런스의 차이
class MyDate{ //클래스의 초기값을 지정함
int year=2006;
int month=4;
int day=1;
}
public class MethodTest05 {
public static void main(String[] args) {
MyDate d; //1. 레퍼런스 변수
System.out.println(d.year+ "/" +d.month+ "/" +d.day);
new MyDate(); //2. 객체 생성되었지만 사용되지 못함
d=new MyDate();
System.out.println(d.year+ "/" +d.month+ "/" +d.day);
}
}
클래스 – 기본 자료형과 레퍼런스의 차이 2
class MyDate{
int year=2006;
int month=4;
int day=1;
}
public class MethodTest06{
public static void main(String[] args) {
int x=7;
int y=x;
MyDate d=new MyDate(); //객체 생성
MyDate t=d;
System.out.println( "x->" +x+ " y->" +y);
System.out.println(d.year+ "/" +d.month+ "/" +d.day); //2006/4/1
System.out.println(t.year+ "/" +t.month+ "/" +t.day); //2006/4/1
y=10;//변수 y의 값을 변경시켜도 x의 값에 영향을 주지 못함
System.out.println( "x->" +x+ " y->" +y);
t.year=2007; t.month=7; t.day=19;
//레퍼런스 변수 d로 접근했을 때에도 변경되어진 값이 출력
System.out.println(d.year+ "/" +d.month+ "/" +d.day); //2007/7/19
System.out.println(t.year+ "/" +t.month+ "/" +t.day); //2007/7/19
}
}
클래스 – 기본 자료형과 레퍼런스의 차이 3
class MyDate{
int year=2006;
int month=4;
int day=1;
}
public class MethodTest07{
public static void main(String[] args) {
MyDate d=new MyDate(); //객체 생성
MyDate t=d;//t가 이미 선언된 d와 동일한 객체를 참조함
System.out.println(d.year+ "/" +d.month+ "/" +d.day); //2006/4/1
System.out.println(t.year+ "/" +t.month+ "/" +t.day); //2006/4/1
t=new MyDate(); //t가 새로 생성된 객체를 가리키므로 d와는 별개로 동작함
t.year=2007; t.month=7;
t.day=19;
System.out.println(d.year+ "/" +d.month+ "/" +d.day); //2006/4/1
System.out.println(t.year+ "/" +t.month+ "/" +t.day); //2007/7/19
}
}
클래스 – 값 전달 방식
class ValueMethod{
void changeInt(int y){
y=10;
}
public class MethodTest08 {
public static void main(String[] args) {
ValueMethod vm=new ValueMethod();
int x=7;
System.out.println( " 함수 호출 전 x->" +x);
vm.changeInt(x);
System.out.println( " 함수 호출 후 x->" +x);
}
}
클래스 – 레퍼런스 전달 방식
class MyDate{
int year=2006;
int month=4;
int day=1;
}
class RefMethod{
void changeDate(MyDate t){
}
}
public class MethodTest09 {
public static void main(String[] args) {
RefMethod rm=new RefMethod();
MyDate d=new MyDate();
System.out.println(" 함수 호출 전 d->" + d.year+ "/" +d.month+ "/" +d.day);
rm.changeDate(d);
System.out.println(" 함수 호출 후 d->" + d.year+ "/" +d.month+ "/" +d.day);
}
}
클래스 - 오류
class MyDate{
int year=2006;
int month=4;
}
class MethodTestB{
public static void main(String[] args){
MyDate d;
System.out.println(d.year+ "/" +d.month+ "/" +d.day);
}
}
클래스 – null 객체
class MyDate{
int year=2006;
int month=4;
int day=1;
}
class MethodTestC{
public static void main(String[] args){
MyDate d=null;
System.out.println(d.year+ "/" +d.month+ "/" +d.day);
System.out.println("정상 종료");
}
}
클래스 – 예외 처리
class MyDate{
int year=2006;
int month=4;
int day=1;
}
class MethodTestD{
public static void main(String[] args){
MyDate d=null;
try{
System.out.println(d.year+ "/" +d.month+ "/" +d.day);
}catch(Exception e){
System.out.println("예외 발생");
}
System.out.println("정상 종료");
}
}
클래스 - 생성자
class MyDate{
private int year;
class MyDate{
private int month;
private int year;
private int day;
private int month;
public void print(){
private int day;
System.out.println(year+ "/" +month+ "/" +day); public MyDate(){
}
System.out.println("[생성자] : 객체가 생성될 때 자
}
동 호출됩니다.");
public class ConstructorTest01 {
}
public static void main(String[] args) {
public void print(){
MyDate d=new MyDate(); //디폴트 생성자 호출 System.out.println(year+ "/" +month+ "/" +day);
d.print();
}
}
}
}
public class ConstructorTest02 {
public static void main(String[] args) {
MyDate d = new MyDate();
d.print();
}
}
클개스 – 생성자의 역할
class MyDate{
private int year;
private int month;
private int day;
public MyDate(){
year=2006;
month=4;
day=1;
}
public void print(){
System.out.println(year+ "/" +month+ "/"
+day);
}
}
public class ConstructorTest03 {
public static void main(String[] args) {
MyDate d=new MyDate();
d.print();
}
}
class MyDate{
private int year;
private int month;
private int day;
public MyDate(){
year=2006; month=4; day=1;
}
public MyDate(int new_year, int new_month, int new_day){
year=new_year;
month=new_month;
day=new_day;
}
public void print(){
System.out.println(year+ "/" +month+ "/" +day);
}
}
public class ConstructorTest04 {
public static void main(String[] args) {
MyDate d=new MyDate();
d.print();
MyDate d2=new MyDate(2007, 7, 19);
d2.print();
}
}
클래스 – 생성자 정의 문제
class MyDate{
private int year;
private int month;
private int day;
public MyDate(int new_year, int new_month, int new_day){
year=new_year;
month=new_month;
day=new_day;
}
public void print(){
System.out.println(year+ "/" +month+ "/" +day);
}
}
public class ConstructorTest05 {
public static void main(String[] args) {
MyDate d=new MyDate();
d.print();
MyDate d2=new MyDate(2007, 7, 19);
d2.print();
}
}
클래스 – 변수 이름의 중복
class MyDate{
private int year;
private int month;
private int day;
//생성자 정의하기
public MyDate(){
}
public MyDate(int new_year, int new_month, int
new_day){
year=new_year; month=new_month;
day=new_day;
}
//전달인자가 객체 속성의 이름과 동일한 메서드
public void SetYear(int year){
//this.year=year;
year=year;
}
public void SetMonth(int new_month){
month=new_month;
}
public void print(){
System.out.println(year+ "/" +month+ "/" +day);
}
}
public class ConstructorTest06 {
public static void main(String[] args) {
MyDate d=new MyDate(2007, 7, 19);
d.print();
d.SetYear(2008); //변경되지 않음
d.print();
//----------------?
d.SetMonth(8); //변경됨
d.print();
//----------------?
}
}
클래스 – this 사용 목적
class MyDate{
private int year;
private int month;
private int day;
public MyDate(){
}
public MyDate(int year, int month, int day){
this.year=year; this.month=month; this.day=day;
}
public void SetYear(int year){ //대입연산자 왼쪽에 this를 붙였기에
his.year=year;
//속성 값이 변경됨
}
public void SetMonth(int month){//대입연산자 왼쪽에 this를 붙였기에
this.month=month;
//속성 값이 변경됨
}
public void print(){
System.out.println(year+ "/" +month+ "/" +day);
}
}
public class ConstructorTest07 {
public static void main(String[] args) {
MyDate d=new MyDate(2007, 7, 19);
d.print();
d.SetYear(2008); //2008년으로 변경
d.SetMonth(8); //8월로 변경
d2.print();
}
}
클래스 – this의 또 다른 사용 목적
class MyDate{
private int year;
private int month;
private int day;
public MyDate(){
this(2006, 1, 1);
}
public MyDate(int new_year){
this(new_year, 1, 1);
}
public MyDate(int new_year, int new_month){
this(new_year, new_month, 1);
}
public MyDate(int new_year, int new_month, int new_day){
year=new_year;
month=new_month;
day=new_day;
}
public void print(){
System.out.println(year+ "/" +month+ "/" +day);
}
}
public class ConstructorTest10 {
public static void main(String[] args) {
MyDate d=new MyDate(2007, 7, 19); //14:에 정의된 생성자 호출
d.print();
MyDate d2=new MyDate(2007, 7);
//11:에 정의된 생성자 호출
d2.print();
MyDate d3=new MyDate(2007);
//8:에 정의된 생성자 호출
d3.print();
MyDate d4=new MyDate();
//5:에 정의된 생성자 호출
d4.print();
}
}
클래스 – 정적 변수
class StaticTest{
static int a=10;
int b=20;
}
class StaticTest01 {
public static void main(String[] args){
System.out.println("StaticTest.a->" + StaticTest.a);
StaticTest s1 = new StaticTest();
StaticTest s2 = new StaticTest();
System.out.println("s1.a->" + s1.a + "\t s2.a->" + s2.a);
System.out.println("s1.b->" + s1.b + "\t s2.b->" + s2.b);
s1.a=100;
System.out.print("s1.a->" + s1.a );
System.out.println("\t s2.a->" + s2.a);
s1.b=200;
System.out.print("s1.b->" + s1.b);
System.out.println("\t s2.b->" + s2.b);
}
}
클래스 – 정적 메서드
class StaticTest{
private static int a=10;
private int b=20;
public static void setA(int new_a){
a = new_a;
}
public static int getA(){
return a;
}
}
public class StaticTest02 {
public static void main(String[] args) {
//System.out.println(StaticTest.a);//a가 private으로 선언되어서 컴파일 에러 발생
System.out.println(StaticTest.getA());
StaticTest s1=new StaticTest();
StaticTest s2=new StaticTest();
s1.setA(10000);
int res1=s1.getA();
System.out.println(res1);
System.out.println(s2.getA());
}
}
클래스 – 정적 메서드 this 사용 오류
class StaticTest{
private static int a=10;
private int b=20;
public static void printA(){ //정적 메서드에서는 this를 사용하지 못함
System.out.println(a);
System.out.println(this.a); //컴파일 에러 발생
}
public void printB(){
//this는 인스턴스 메서드에서 여러 객체에 의해서
System.out.println(this.b); //메서드가 호출될 때 이를 구분하기 위해서 사용된다.
}
}
public class StaticTest03 {
public static void main(String[] args) {
StaticTest.printA();
StaticTest s1 = new StaticTest();
StaticTest s2 = new StaticTest();
s1.printB();
s2.printB();
}
}
클래스 정적 메서드 인스턴스 변수 사용 오류
class StaticTest{
private static int a=10;
private int b=20;
public static void printA(){
System.out.println(a);
System.out.println(b); //컴파일에러발생
}
public void printB(){
System.out.println(b);
}
}
public class StaticTest04 {
public static void main(String[] args) {
StaticTest.printA();
StaticTest s1 = new StaticTest();
StaticTest s2 = new StaticTest();
s1.printB();
s2.printB();
}
}
클래스 – 정적 메서드/변수 사용
class StaticTest06 {
public static void main(String[] args) {
int a=40, b=30, c=10;
int res;
res=Math.max(a, b);
System.out.println(a + "와" + b +" 중최대값: "+res);
res=Math.max(b, c);
System.out.println(b + "와" + c +" 중최대값: "+res);
}
}
class StaticTest07 {
public static void main(String[] args) {
System.out.println(Math.PI);
int r=5;
double area;
area=r*r*Math.PI;
System.out.println("반지름이 "+r+"인 원의 면적 "+ area);
}
}
패캐지 import
package packTest.packOne;
public class ClassOne {
public void print(){
System.out.println("packOne 패키지의ClassOne 클래스의print 메서
드");
}
}
public class PackageTest01 {
public static void main(String[] args) {
Random r = new Random();
for(int i=0; i<10; i++)
System.out.println("0 ~ 100 범위의 임의 숫자는 " + r.nextInt(100));
}
}
public class PackageTest02 {
public static void main(String[] args) {
java.util.Random r = new java.util.Random();
for(int i=0; i<10; i++)
System.out.println("0 ~ 100 범위의 임의 숫자는 " + r.nextInt(100));
}
}
패키지 import 2
import java.util.*;
public class PackageTest01 {
public static void main(String[] args) {
Random r = new Random();
for(int i=0; i<10; i++)
System.out.println("0 ~ 100 범위의 임의 숫자는 " + r.nextInt(100));
}
}
상속 – 슈퍼 클래스, 서브 클래스
class Parent{
public void parentPrn( ){
System.out.println("슈퍼 클래스 메서드는 상속된다.");
}
}
//Parent를 슈퍼 클래스로 하는 서브 클래스 Child 정의
class Child extends Parent{
public void childPrn( ){
System.out.println("서브 클래스 메서드는 슈퍼가 사용 못한다.");
}
}
class SuperSub01{
public static void main(String[] args){
Child c = new Child( ); //서브 클래스로 객체를 생성
c.parentPrn( );
//슈퍼 클래스에서 상속 받은 메서드 호출
c.childPrn( );
//서브 클래스 자기 자신의 메서드 호출
System.out.println("-------------------------------------->> ");
Parent p = new Parent( ); //슈퍼 클래스로 객체 생성
p.parentPrn( );
//슈퍼 클래스 자기 자신의 메서드 호출
//p.childPrn( );
//서브 클래스 메서드는 가져다 사용 못함
}
}
상속 – 코드의 재활용
class Point2D{
private int x;
private int y;
public int getX( ){
return x;
}
public void setX(int new_X){
x=new_X;
}
public int getY( ){
return y;
}
public void setY(int new_Y){
y=new_Y;
}
}
class Point3D extends Point2D{
private int z;
public int getZ( ){
return z;
}
public void setZ(int new_Z){
z=new_Z;
}
}
class SuperSub00{
public static void main(String[] args){
Point3D pt=new Point3D( );
pt.setX(10); //상속받아 사용
pt.setY(20); //상속받아 사용
pt.setZ(30); //자신의 것 사용
System.out.println( pt.getX( )//상속받아 사용
+", "+ pt.getY( )//상속받아 사용
+", "+ pt.getZ( ));//자신의 것 사용
}
}
교재 210페이지 참조
상속 – protected, private 접근 지정자
class Point2D{
protected int x=10;
// private int x=10;
protected int y=20;
}
class Point3D extends Point2D{
protected int z=30;
public void print( ){
System.out.println( x +", "+y+","+z);
}
}
class SuperSub04{
public static void main(String[] args){
Point3D pt=new Point3D( );
pt.print( );
}
}
상속 – protected, private 접근 지정자
package packTest.packOne;
public class AccessTest {
private int a=10; //[1] private
int
b=20; //[2] 기본 접근 지정자
protected int c=30; //[3] protected
public
int d=40; //[4] public
public void print( ){
System.out.println("AccessTest의 print");
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}
import packTest.packOne.AccessTest;
//AccessTest의 서브 클래스로 SubOne을 설계
class SubOne extends AccessTest {
void subPrn( ){
System.out.println(a); //[1. Sub] private -X
System.out.println(b); //[2. Sub] 기본 접근 지정자-X
System.out.println(c); //[3. Sub] protected -O
System.out.println(d); //[4. Sub] public -0
}
}
//AccessTest랑 상속관계가 없는 클래스
class SuperSubA{
public static void main(String[] args){
AccessTest at=new AccessTest( );
at.print( );
System.out.println("main");
System.out.println(at.a); //[1. main] private -X
System.out.println(at.b); //[2. main] 기본 접근 지정자
-X
System.out.println(at.c); //[3. main] protected -X
System.out.println(at.d); //[4. main] public -O
}
}
상속 – 메서드 오버라이딩
class Parent{
public void parentPrn( ){
System.out.println("슈퍼 클래스
}
}
//Parent를 슈퍼 클래스로 하는 서브
class Child extends Parent{
public void parentPrn( ){
System.out.println("서브 클래스
}
public void childPrn( ){
System.out.println("서브 클래스
}
}
: ParentPrn 메서드");
클래스 Child 정의
: ParentPrn 메서드");
: ChildPrn 메서드");
class SuperSub05{
public static void main(String[] args){
Child c = new Child( );
//서브 클래스로 객체를 생성
c.parentPrn( );
//오버라이딩된 서브 클래스의 메서드 호출
c.childPrn( );
//서브 클래스 자기 자신의 메서드 호출
System.out.println("-------------------------------------------->>
");
Parent p = new Parent( );
//슈퍼 클래스로 객체를 생성
p.parentPrn( );
//슈퍼 클래스(자기 자신)의 메서드 호출
}
}
상속 – super 레퍼런스 변수
class Parent{
public void parentPrn( ){
System.out.println("슈퍼 클래스 : ParentPrn 메서드");
}
}
//Parent를 슈퍼 클래스로 하는 서브 클래스 Child 정의
class Child extends Parent{
//슈퍼 클래스에 있는 ParentPrn 메서드를 오버라이딩하면
//Child로 선언된 객체는 슈퍼 클래스의 메서드가 은닉되어 상속 받지 못하게 된다.
public void parentPrn( ){
super.parentPrn();
System.out.println("서브 클래스 : ParentPrn 메서드");
}
public void childPrn( ){
System.out.println("서브 클래스 : ChildPrn 메서드");
}
}
class SuperSub05{
public static void main(String[] args){
Child c = new Child( );
//서브 클래스로 객체를 생성
c.parentPrn( );
//오버라이딩된 서브 클래스의 메서드 호출
c.childPrn( );
//서브 클래스 자기 자신의 메서드 호출
System.out.println("-------------------------------------------->> ");
Parent p = new Parent( );
//슈퍼 클래스로 객체를 생성
p.parentPrn( );
//슈퍼 클래스(자기 자신)의 메서드 호출
}
}
상속 – super 레퍼런스 변수 2
class Point2D{
protected int x=10; //은닉 변수
protected int y=20; //혹은 쉐도우 변수
}
class Point3D extends Point2D{
protected int x=40; //슈퍼 클래스에 존재하는 멤버변수를
protected int y=50; //서브 클래스에 다시 한 번 정의함
protected int z=30;
public void print( ){
System.out.println( x +", "+y+", "+z); //x와 y는 재 정의된 Point3D 클래스 소속
}
public void print02( ){
System.out.println(super.x+", "+super.y+", "+z); //Point2D 클래스 소속 멤버변수로 접근
}
}
class SuperTest04{
public static void main(String[] args){
Point3D pt=new Point3D( );
pt.print( ); //40, 50, 30 // Point3D의 x, y
pt.print02( ); //10, 20, 30 // Point2D의 x, y
}
}
상속 – 생성자의 호출
class Point2D{
protected int x=10;
protected int y=20;
public Point2D( ){
System.out.println("슈퍼 클래스인 Point2D 생성자 호출");
}
}
class Point3D extends Point2D{
protected int z=30;
public void print( ){
System.out.println(x+", "+y+","+z);
}
public Point3D( ){
System.out.println("서브 클래스인 Point3D 생성자 호출");
}
}
class SuperTest05{
public static void main(String[] args){
Point3D pt=new Point3D( );
pt.print( );
}
}
상속 – 생성자 호출 문제
class Point2D{
protected int x=10;
protected int y=20;
/*
public Point2D( ){
System.out.println("슈퍼 클래스인 Point2D 생성자 호출");
}
*/
public Point2D(int xx, int yy){
x=xx; y=yy;
}
}
class Point3D extends Point2D{
protected int z=30;
public void print( ){
System.out.println(x+", "+y+","+z);
}
public Point3D( ){
System.out.println("서브 클래스인 Point3D 생성자 호출");
}
}
class SuperTest06{
public static void main(String[] args){
Point3D pt=new Point3D( );
pt.print( );
}
}
class Point2D{
protected int x=10;
protected int y=20;
public Point2D( ){
System.out.println("슈퍼 클래스인 Point2D 생성자 호출");
}
public Point2D(int xx, int yy){
x=xx; y=yy;
}
}
class Point3D extends Point2D{
protected int z=30;
public void print( ){
System.out.println(x+", "+y+", "+z);
}
public Point3D( ){
super(123, 456);
System.out.println("서브 클래스인 Point3D 생성자 호출");
}
public Point3D(int xx, int yy, int zz){
x=xx; y=yy; z=zz;
}
}
class SuperTest07{
public static void main(String[] args){
Point3D pt=new Point3D( );
pt.print( );
Point3D pt02=new Point3D(1, 2, 3);
pt02.print( );
}
}
상속 – 업 캐스팅
class Parent{
public void parentPrn( ){
System.out.println("슈퍼 클래스 : ParentPrn 메서드");
}
}
//Parent를 슈퍼 클래스로 하는 서브 클래스 정의
class Child extends Parent{
public void childPrn( ){
System.out.println("서브 클래스 : ChildPrn 메서드");
}
}
class RefTest01{
public static void main(String[] args){
Child c = new Child(); //서브 클래스로 객체를 생성
//Child 객체로 접근해서 호출할 수 있는 메서드는 2개
c.parentPrn(); //부모로부터 상속 받은 메서드
c.childPrn();
//자신의 메서드
Parent p;
//슈퍼 클래스형 레퍼런스 변수 선언
p=c;
//암시적으로 업 캐스팅이 일어남
p.parentPrn(); //업 캐스팅 후에는 부모로부터 상속받은 메서드만 호출할 수 있다,
//p.childPrn(); //컴파일 에러가 발생하게 된다.
}
}
상속 – 다운 캐스팅
class RefTest02{
public static void main(String[] args){
Parent p = new Parent(); //슈퍼 클래스로 인스턴스 선언
Child c;
//서브 클래스로 레퍼런스 변수 선언
//서브 클래스형 레퍼런스 변수에 슈퍼 클래스의 레퍼런스 값을 대입하면
c= p; //이를 DownCasting 이라하는데 컴파일러 에러가 발생한다.
}
}
class RefTest03{
public static void main(String[] args){
// Parent p = new Parent( ); // super 클래스 인스턴스 선언
Parent p = new Child( ); //서브 클래스로 인스턴스 선언
p.parentPrn();
//p.childPrn();//-컴파일 에러
Child c;
//서브 클래스로 레퍼런스 변수 선언
System.out.println("----------------------------->>");
//서브 클래스 레퍼런스 변수에 슈퍼 클래스의 레퍼런스 값이 대입됨
c = (Child) p; //강제 형변환으로 다운 캐스팅 (단, 인스턴스가 Child 형인 경우)
c.parentPrn();
c.childPrn();
}
}
상속 – instanceof 1
class HandPhone {
String model; //모델명
String number;//전화번호
public HandPhone(){
}
public HandPhone(String m, String n){
model=m;
number=n;
}
}
class DicaPhone extends HandPhone{
String pixel; //화소수
public DicaPhone( ){
}
public DicaPhone(String m, String n, String p){
super(m, n);
pixel=p;
}
public void prnDicaPhone(){
System.out.println(model+":"+number+":"+pixel);
}
}
상속 – instanceof 2
class RefTest05 {
public static void main(String[] args){
DicaPhone dp=new DicaPhone("에버-5500","010-3346-1980","256");
// instanceof 는 좌변의 객체가 우변의 자손인지를 판별해 주는 연산자
dp.prnDicaPhone();
System.out.println("-----------------------");
if (dp instanceof DicaPhone){ //dp는 DicaPhone입니까?
System.out.println("dp는 DicaPhone이다.");
}
if (dp instanceof HandPhone){ //dp는 HandPhone입니까?
System.out.println("dp는 HandPhone 이다.");
HandPhone hh=dp;
System.out.println("그러므로 HandPhone으로 형변환 가능함");
System.out.println("dp는 HandPhone이 가진 기능을 모두 다 포함");
}
System.out.println("-----------------------");
HandPhone hp = new HandPhone( );
if (hp instanceof DicaPhone){ //p는 DicaPhone입니까?
System.out.println("hp는 DicaPhone 이다.");
}
else{
System.out.println("hp는 DicaPhone이 아니다.");
System.out.println("그러므로 DicaPhone으로 형변환 불가능함.");
System.out.println("hp는 DicaPhone이 가진 기능을 모두 다 포함하지 못함");
}
}
}
상속 – 메서드 오버라이딩으로 인한 은닉
class Parent{
public void parentPrn( ){
System.out.println("슈퍼 클래스 : ParentPrn 메서드");
}
}
class Child extends Parent{
public void parentPrn( ){
System.out.println("서브 클래스 : 오버라이딩된 ParentPrn 메서드");
}
public void childPrn( ){
System.out.println("서브 클래스 : ChildPrn 메서드");
}
}
class RefTest06{
public static void main(String[] args){
Child c = new Child(); //서브 클래스로 객체를 생성
//레퍼런스와 객체의 자료형이 동일하면
c.parentPrn(); //자신의 기능들이 호출된다.
Parent p;
//슈퍼 클래스형 레퍼런스 변수 선언
p=c; //업 캐스팅
//업 캐스팅 후에도 슈퍼 클래스의 parentPrn 메서드는 은닉되고
p.parentPrn(); //서브 클래스에 오버라이딩된 메서드가 호출된다.
}
}
추상 클래스 및 추상 메서드
class AbstractClass{//추상 클래스가 아닌 클래스에서
abstract void Method01();//추상 메서드를 가질 경우 컴파일 에러
}
abstract class AbstractClass {
abstract void print( String Message );
}
class AbstractClass {
abstract void print( String Message );
}
추상 클래스 상속
package javaapplication5;
/**
*
* @author 장성현
*/
abstract class ShapeClass {
abstract void draw();
}
class Circ extends ShapeClass {
void draw() {
System.out.println("타원을 그린다.");
}
}
class Rect extends ShapeClass {
void draw() {
System.out.println("사각형을 그린다.");
}
}
class Tria extends ShapeClass {
void draw() {
System.out.println("삼각형을 그린다.");
}
}
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Circ c = new Circ();
Rect r = new Rect();
Tria t = new Tria();
c.draw();
r.draw();
t.draw();
}
}
Final 변수 및 메서드
class FinalMember {
final int a=10;
public void setA(int a){
// this.a=a;
}
}
public class finaltest{
public static void main(String[] args) {
FinalMember ft= new FinalMember();
ft.setA(100);
System.out.println(ft.a);
}
}
class FinalMethod{
String str="Java ";
//public void setStr(String s) {
//final 붙이면 서브 클래스에서 오버라이딩이 불가.
public final void setStr(String s) {
str=s;
System.out.println(str);
}
}
class FinalEx extends FinalMethod{
int a=10; // final 붙이면 밑에서 a값 대입 불가.
public void setA(int a) {
this.a=a;
}
public void setStr(String s) {
str+=s;
System.out.println(str);
}
}
public class FinalTest02{
public static void main(String[] args) {
FinalEx ft= new FinalEx( );
ft.setA(100);
ft.setStr("hi");// 슈퍼 클래스의 setStr을 실행.
FinalMethod ft1=new FinalMethod( );
ft1.setStr("hi");// 자신의 클래스의 setStr을 실행.
}
}
Final 클래스
final class FinalClass{
String str="Java ";
public void setStr(String s){
str=s;
System.out.println(str);
}
}
class FinalEx extends FinalClass{
int a=10;
public void setA(int a) {
this.a=a;
}
public void setStr(String s){
str+=s;
System.out.println(str);
}
}
public class FinalTest03{
public static void main(String[] args) {
FinalEx fe= new FinalEx( );
}
}
상속의 제한
abstract class Hello{
public abstract void sayHello(String name);
}
abstract class GoodBye{
public abstract void sayGoodBye(String name);
}
//class SubClass extends GoodBye{
class SubClass extends Hello{//추상 클래스 Hello를 상속
public void sayHello(String name){//오버라이딩 한 것이
System.out.println(name+"씨 안녕하세요!");
}
public void sayGoodBye(String name){
//추상 클래
System.out.println(name+"씨 안녕히 가세요!");
}
}
class AbstractTest02{
public static void main(String[] args) {
SubClass test= new SubClass();
test.sayHello(args[0]);
test.sayGoodBye(args[0]);
}
}
인터페이스 정의 및 다중 상속
abstract class Hello{
public abstract void sayHello(String name);
}
abstract class GoodBye{
public abstract void sayGoodBye(String name);
}
//class SubClass extends GoodBye{
class SubClass extends Hello{//추상 클래스 Hello를 상속
public void sayHello(String name){//오버라이딩 한 것이
System.out.println(name+"씨 안녕하세요!");
}
public void sayGoodBye(String name){
//추상 클래
System.out.println(name+"씨 안녕히 가세요!");
}
}
class AbstractTest02{
public static void main(String[] args) {
SubClass test= new SubClass();
test.sayHello(args[0]);
test.sayGoodBye(args[0]);
}
}
interface IHello{
public abstract void sayHello(String name);
}
interface IGoodBye{
public abstract void sayGoodBye(String name);
}
//두 인터페이스로부터 상속을 받는 클래스 설계
class SubClass implements IHello, IGoodBye{
public void sayHello(String name){
System.out.println(name+"씨 안녕하세요!");
}
public void sayGoodBye(String name){
System.out.println(name+"씨 안녕히 가세요!");
}
}
class AbstractTest05{
public static void main(String[] args) {
SubClass test= new SubClass();
test.sayHello(args[0]);
test.sayGoodBye(args[0]);
}
}
인터페이스 정의 – 속성 정의
//인터페이스(IColor)므로 다중 상속 가능
interface IColor{
int RED=1;
//상수(public static final 로 인식)
public static final int GREEN=2;
//상수
public static final int BLUE=3;
//상수
void setColor(int c);
//추상메서드 (public abstract 로 인식)
public abstract int getColor();
//추상메서드
}
//클래스(AbsColor)이므로 다중 상속 불가능 단일 상속만,
abstract class AbsColor implements IColor{
int color=GREEN;
//변수도 가질 수 있디.
public void setColor(int c){
//구현된 메서드도 가질 수 있다.
color=c;
}
}
class SubClass extends AbsColor{
public int getColor(){
return color;
}
}
class AbstractTest07{
public static void main(String[] args) {
SubClass test= new SubClass();
test.setColor(IColor.RED);
System.out.println(test.getColor());
}
}
인터페이스 정의 – 메서드 오버라이딩
interface IHello{
void sayHello(String name);
}
class Hello implements IHello{
public void sayHello(String name){
//void sayHello(String name){
System.out.println(name+"씨 안녕하세요!");
}
}
class finaltest{
public static void main(String[] args) {
Hello obj= new Hello();
obj.sayHello(args[0]);//윤정
}
}
자주 사용하는 자바 클래스 - Object
class Point{
}
class ObjectTest00 {
public static void main(String[] args){
Point obj = new Point( );
System.out.println("클래스 이름 : "+ obj.getClass() );
System.out.println("해쉬 코드 : "+ obj.hashCode() );
System.out.println("객체 문자열 : "+ obj.toString() );
System.out.println("----------------------------------");
Point obj02 = new Point( );
System.out.println("클래스 이름 : "+ obj02.getClass() );
System.out.println("해쉬 코드 : "+ obj02.hashCode() );
System.out.println("객체 문자열 : "+ obj02.toString() );
}
}
자주 사용하는 자바 클래스 – Object 2
// Object 클래스의 메서드 오버라이딩
class Point{
int x, y;
public Point( ){ }
this.x=x;
this.y=y;
}
public String toString( ){
String str;
str="( " + x + ", " + y + " )";
return str;
}
}
class ObjectTest02 {
public static void main(String[] args) {
Point pt = new Point(10, 20);
System.out.println(pt);
}
}
자주 사용하는 자바 클래스 – Object 3
class ObjectTestA{
public static void main(String[] args) {
int a=10, b=10;
if(a==b)
System.out.println("같다");
else
System.out.println("다르다");
String str01=new String("안녕");
String str02=new String("안녕");
//두 레퍼런스 변수가 같은 힙영역을 가리키는 지 판별하는 ==연산자
if(str01==str02)
System.out.println("같다");
else
System.out.println("다르다");
//두 객체의 내용이 같은지 판별하는 equals 메서드
if(str01.equals(str02))
System.out.println("같다");
else
System.out.println("다르다");
}
}
자주 사용하는 자바 클래스 – Object 3
class Point{
int x, y;
public Point( ){ }
public Point(int x, int y){
this.x=x;
this.y=y;
}
public boolean equals(Object obj){
Point ptTmp = (Point)obj; //다운 캐스팅한 후에
//두 멤버변수 x, y 값이 각각 같은지 판별한다.
if ( (x == ptTmp.x) && (y == ptTmp.y))
return true;
else
return false;
}
}
class ObjectTest03{
public static void main(String[] args) {
Point pt01 = new Point(10, 20);
Point pt02 = new Point(10, 20);
if(pt01==pt02)
System.out.println("두 레퍼런스가 같습니다.");
else
System.out.println("두 레퍼런스가 다릅니다.");
if(pt01.equals(pt02))
System.out.println("두 객체의 내용이 같습니다.");
else
System.out.println("두 객체의 내용이 다릅니다.");
}
}
자주 사용하는 자바 클래스 – Wapper 클래스
자료형 변환
public class ex05_B02 {
public static void main(String[] args) {
int num01,num02, max;
num01 = Integer.parseInt(args[0]);
num02 = Integer.parseInt(args[1]);
if(num01>num02)
max=num01;
else
max=num02;
System.out.println(" 큰 값은 -> " + max);
}
}
class WrapperTest01 {
public static void main(String[] args) {
Integer num01 = new Integer(10);
Integer num02 = new Integer("20");
//숫자 데이터를 포함한 Wrapper 클래스는 XXXValue
메서드를 호출하여 자바 기본형 데이터를 얻을 수 있다.
int n01=num01.intValue();
int n02=num01.intValue();
int sum;
sum=n01+n02;
System.out.println("두 정수의 합은 -> " + sum);
//Integer 객체에 저장된 정수값을 2진수, 8진수, 16진수
형태의 문자열로 변환
System.out.println("합을 2진수로 -> " + Integer.toBinaryString(sum));
System.out.println("합을 8진수로 -> " + Integer.toOctalString(sum));
System.out.println("합을 16진수로 -> " + Integer.toHexString(sum));
}
}
자주 사용하는 자바 클래스 – Wapper 클래스
오토 빅싱
class WrapperTestA {
public static void main(String[] args) {
int n01=10;
int n02;
Integer num01 ; //Integer 객체 생성
Integer num02= new Integer(20) ;
num01 = n01; //오토 박싱
n02 = num02; //오토 언 박싱
System.out.println(n01 + ", " + num01);
System.out.println(n02 + ", " + num02);
}
}
문자열 관련 클래스 – String 클래스
class StringTest00 {
public static void main(String[] args) {
String str1 = new String("Java Programming");
String str2 = new String("Java Programming");
if(str1==str2)
System.out.println("같다");
else
System.out.println("다르다");
// 상수 대입, 같은 내용일 경우 한번만 메모리 할당
String str3 = "Java Programming";
String str4 = "Java Programming";
if(str3==str4)
System.out.println("같다");
else
System.out.println("다르다");
}
}
문자열 관련 클래스 – StringBuffer 클래스
class StringTest03 {
public static void main(String[] args) {
StringBuffer str01 = new StringBuffer(); //StringBuffer 객체 생성
str01.append("Java");
//현재 문자열 끝에 첨부
System.out.println("str01의 값은-> " + str01.toString()); //........"Java"
str01.append(" Progamming");
//현재 문자열 끝에 첨부
System.out.println("str01의 값은-> " + str01.toString()); //........"Java Progamming"
str01.replace(0, 4, "MFC");
//0부터 4사이의 내용을 “MFC"로 교환
System.out.println("str01의 값은-> " + str01.toString()); //........"MFC Progamming"
//substring에서 지정한 위치에서부터 시작하여 마지막 문자까지 반환
String str02 = str01.substring(3) //.............................................." Progamming"
//str01은 그대로 MFC "Progamming "
System.out.println("str01의 값은-> " + str01);
System.out.println("str02의 값은-> " + str02);
//....................."MFC Progamming"
//....................." Progamming"
str01.deleteCharAt(0); //0번째 위치의 한문자를 지운다.
System.out.println("str01의 값은-> " + str01.toString()); //........"FC Progamming"
str01.reverse();
//문자열의 순서를 뒤집는다.
System.out.println("str01의 값은-> " + str01.toString()); //........"gnimmagorP CF"
}
}
문자열 관련 클래스 – StringTokenizer클래스
import java.util.*;
class StringTest04 {
public static void main(String[] args) {
StringTokenizer str = new StringTokenizer("전도연#김혜수#전지현#김태희", "#");
int cnt = str.countTokens(); //파싱된 문자열이 모두 몇 개인지 되는지 알려줌
System.out.println("파싱할 문자열의 총갯수-> " + cnt);
while(str.hasMoreTokens())
//토큰이 있으면
System.out.println(str.nextToken()); //차례대로 파싱된 문자열을 얻어온다.
}
}
AWT 를 이용한 GUI 작성 – WindowEvent 처리
import java.awt.*;
import java.awt.event.*;
class FrameEvent extends Frame {
public FrameEvent( ) {
super("윈도우 이벤트");
setSize(300,200);
setVisible(true);
addWindowListener( new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
} );
}
}
public class FrameTest02{
public static void main(String[] args) {
new FrameEvent();
}
}
교재 358 내부 클래스 참조
교재 361 내부 무명 클래스 참조
AWT 를 이용한 GUI 작성 – WindowEvent 처리
package awttest;
import java.awt.*;
import java.awt.event.*;
class DemoEvent extends WindowAdapter {
private Frame Event_Frame;
public DemoEvent() {
}
public DemoEvent( Frame f ) {
Event_Frame = f;
}
public void windowClosing( WindowEvent e ) {
Event_Frame.dispose();
System.exit(0);
}
}
public class Main {
public static void main(String[] args) {
// TODO code application logic here
Frame f = new Frame("Frame Demo"); //프레임 객체 생성
f.setSize(200, 200);
f.setVisible( true );
f.addWindowListener( new DemoEvent( f ) );
}
}
AWT 컴포넌트 배치 - FlowLayout
import java.awt.*;
import java.awt.event.*;
class FrameEx extends Frame {
public FrameEx( ) {
setLayout(new FlowLayout());
add(new Button("Button 01"));
add(new Button("Button 02"));
add(new Button("Button 03"));
add(new Button("Button 04"));
add(new Button("Button 05"));
setSize(300,200);
setVisible(true);
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
} );
}
}
public class FrameTest03{
public static void main(String[] args) {
new FrameEx( );
}
}
AWT 컴포넌트 배치 - BorderLayout
import java.awt.*;
import java.awt.event.*;
class FrameEx extends Frame {
public FrameEx( ) {
setLayout(new BorderLayout());
add(new Button("Button 01"), "North");
add(new Button("Button 02"), "West");
add(new Button("Button 03"), "Center");
add(new Button("Button 04"), "East");
add(new Button("Button 05"), "South");
setSize(300,200);
setVisible(true);
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
} );
}
}
public class FrameTest04{
public static void main(String[] args) {
new FrameEx( );
}
}
AWT 컴포넌트 배치 - GridLayout
import java.awt.*;
import java.awt.event.*;
class FrameEx extends Frame {
public FrameEx( ) {
setLayout(new GridLayout(3, 2));
add(new Button("Button 01"));
add(new Button("Button 02"));
add(new Button("Button 03"));
add(new Button("Button 04"));
add(new Button("Button 05"));
setSize(300,200);
setVisible(true);
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
} );
}
}
public class FrameTest05{
public static void main(String[] args) {
new FrameEx( );
}
}
AWT 컴포넌트 배치 - GridBagLayout
import java.awt.*;
import java.awt.event.*;
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
}
);
class GridBagLayoutTest extends Frame{
GridBagLayout grid;
GridBagConstraints con;
public GridBagLayoutTest(){
}
grid = new GridBagLayout();
private void addCom(Component c, int x, int y, int w, int h){
setLayout(grid);
add(c);
con.gridx=x;
con = new GridBagConstraints();
con.gridy=y;
con.fill=GridBagConstraints.BOTH;
con.gridwidth=w;
con.weightx=1.0;
con.gridheight=h;
con.weighty=1.0;
grid.setConstraints(c, con);
}
Button btn1=new Button("버튼 1");
}
addCom(btn1, 0, 0, 2, 1);
Button btn2=new Button("버튼 2");
class LayoutTest02
addCom(btn2, 2, 0, 1, 2);
{
Button btn3=new Button("버튼 3");
public static void main(String[] args)
addCom(btn3, 0, 1, 1, 1);
{
Button btn4=new Button("버튼 4");
new GridBagLayoutTest();
addCom(btn4, 1, 1, 1, 1);
}
}
setSize(200,200);
setVisible(true);
AWT 컴포넌트 배치 - CardLayout
class CardLayoutTest extends Frame {
CardLayout card;
Panel
[] panel ;
Color
[] color = {Color.red, Color.blue,
Color.yellow,Color.green,Color.cyan};
MouseHandle mouse;
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
} );
}
public CardLayoutTest(){
card = new CardLayout();
setLayout(card);
class MouseHandle extends MouseAdapter{
public void mouseClicked(MouseEvent e){
card.next(CardLayoutTest.this);
}
}
panel= new Panel[5];
mouse = new MouseHandle();
}
for(int i = 0 ; i < 5 ; i++){
panel[i] = new Panel();
panel[i].setBackground(color[i]);
add((new Integer(i)).toString(), panel[i]);
panel[i].addMouseListener(mouse);
}
setSize(200,200);
setVisible(true);
class LayoutTest01{
public static void main(String [] args){
new CardLayoutTest();
}
}
AWT 컴포넌트 배치 - Pannel
import java.awt.*;
import java.awt.event.*;
class FrameEx extends Frame {
Panel pan01, pan02, pan03;
public FrameEvent06( ) {
pan01 = new Panel();
pan02 = new Panel();
pan03 = new Panel();
pan03.add(new Button("Button 04"));
pan03.add(new Button("Button 05"));
setSize(300,130);
setVisible(true);
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
} );
pan01.setBackground(Color.green);
pan02.setBackground(Color.blue);
pan03.setBackground(Color.red);
add(BorderLayout.NORTH, pan01);
add(BorderLayout.CENTER, pan02);
add(BorderLayout.SOUTH, pan03);
pan01.add(new Button("Button 01"));
pan01.add(new Button("Button 02"));
pan02.add(new Button("Button 03"));
}
}
public class FrameTest06{
public static void main(String[] args) {
new FrameEx( );
}
}
컴포넌트 이벤트 처리 – interface 상속 외부 객체 단점
import java.awt.*;
import java.awt.event.*;
setSize(300,200);
setVisible(true);
class FrameEvent extends Frame {
Button redBtn, blueBtn;
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
} );
public FrameEvent( ) {
setLayout(new FlowLayout());
redBtn = new Button("빨간 색");
blueBtn = new Button("파란 색");
add(redBtn);
add(blueBtn);
ButtonListener handler = new ButtonListener( );
redBtn.addActionListener(handler);
blueBtn.addActionListener(handler);
}
}
class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand( ));
}
}
public class EventTest01{
public static void main(String[] args) {
new FrameEvent( );
}
}
컴포넌트 이벤트 처리 – interface 상속 외부 객체 단점
import java.awt.*;
import java.awt.event.*;
class FrameEvent extends Frame {
Button redBtn, blueBtn;
public FrameEvent( ) {
setLayout(new FlowLayout());
redBtn = new Button("빨간 색");
blueBtn = new Button("파란 색");
add(redBtn);
add(blueBtn);
class ButtonListener implements ActionListener{
Frame frm=null;
public ButtonListener(){
}
public ButtonListener(Frame value){
frm=value;
}
public void actionPerformed(ActionEvent e){
if(e.getActionCommand( )=="빨간 색")
frm.setBackground(Color.red);
else
frm.setBackground(Color.blue);
}
};
ButtonListener handler = new ButtonListener(this);
public class EventTest02{
redBtn.addActionListener(handler);
public static void main(String[] args) {
blueBtn.addActionListener(handler);
new FrameEvent( );
}
setSize(300,200);
}
setVisible(true);
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
} );
}
}
컴포넌트 이벤트 처리 – Frame의 interface 상속
import java.awt.*;
import java.awt.event.*;
public void actionPerformed(ActionEvent e) {
if(e.getSource( ) == redBtn)
this.setBackground(Color.red);
else if(e.getSource( ) == blueBtn)
this.setBackground(Color.blue);
}
class FrameEvent extends Frame implements
ActionListener{
Button redBtn, blueBtn;
public FrameEvent( ) {
setLayout(new FlowLayout());
redBtn = new Button("빨간 색");
blueBtn = new Button("파란 색");
add(redBtn);
add(blueBtn);
redBtn.addActionListener(this);
blueBtn.addActionListener(this);
setSize(300,200);
setVisible(true);
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
} );
}
}
public class EventTest03{
public static void main(String[] args) {
new FrameEvent( );
}
}
컴포넌트 이벤트 처리 – interface 상속 문제점
import java.awt.*;
import java.awt.event.*;
class ExitEventFrame extends Frame implements WindowListener{
public ExitEventFrame ( ){
this.addWindowListener(this);
setSize(200,200);
setVisible(true);
}
public void windowClosing(WindowEvent e){
dispose( );
System.exit(0);
}
public void windowActivated(WindowEvent e){ }
public void windowClosed(WindowEvent e){ }
public void windowDeactivated(WindowEvent e){ }
public void windowDeiconified(WindowEvent e){ }
public void windowIconified(WindowEvent e){ }
public void windowOpened(WindowEvent e){ }
}
public class EventTest04{
public static void main (String args[]){
new ExitEventFrame();
}
}
컴포넌트 이벤트 처리 – Adapter 상속 문제점
import java.awt.*;
import java.awt.event.*;
class ExitFrameEvent extends Frame {
public ExitFrameEvent( ) { //생성자
setSize(200,200);
setVisible(true);
addWindowListener( new SubClass( ) );
}
}
class SubClass extends WindowAdapter{
public void windowClosing(WindowEvent e) {
//dispose( );//자원 해제
System.exit(0);
}
}
public class EventTest05{
public static void main(String[] args) {
new ExitFrameEvent( );
}
}
컴포넌트 이벤트 처리 – Adapter 상속 무명 내부 클래스
import java.awt.*;
import java.awt.event.*;
class ExitFrameEvent extends Frame {
public ExitFrameEvent( ) {
setSize(200,200);
setVisible(true);
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
} );
}
}
public class EventTest06{
public static void main(String[] args) {
new ExitFrameEvent( );
}
}
컴포넌트 이벤트 처리 – Adapter 상속 내부 클래스
import java.awt.*;
import java.awt.event.*;
class ExitFrameEvent extends Frame {
public ExitFrameEvent( ) {
setSize(200,200);
setVisible(true);
addWindowListener( new SubClass( ) );
class SubClass extends WindowAdapter{
public void windowClosing(WindowEvent e) {
dispose( );
System.exit(0);
}
}
}
}
public class EventTest07{
public static void main(String[] args) {
new ExitFrameEvent( );
}
}
class Outer{
int data=100;
class Inner{
public void printData() {
System.out.println(data+"입니다.");
}
}
}
public class EventTest08{
public static void main(String[] args) {
//외부 클래스로 객체 생성
Outer outObj=new Outer();
//내부 클래스로 객체 생성
Outer.Inner inObj= outObj.new Inner();
inObj.printData();
}
}
다양한 컴포넌트 이벤트 처리 – 텍스트 입력 받기
import java.awt.*;
import java.awt.event.*;
setSize(400,100);
setVisible(true);
class FrameEvent extends Frame {
Panel p1, p2;
TextField txtID;
TextField txtPW;
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
}
);
public FrameEvent( ) {
setLayout(new BorderLayout( ));
p1=new Panel( );
p2=new Panel( );
txtID=new TextField(20);
txtPW=new TextField(20);
txtPW.setEchoChar('*');
p1.add(new Label("아 이 디 : "));
p1.add(txtID);
this.add(p1, BorderLayout.NORTH);
p2.add(new Label("패스 워드 : "));
p2.add(txtPW);
this.add(p2, BorderLayout.CENTER);
}
}
public class ComTest01{
public static void main(String[] args) {
new FrameEvent( );
}
}
다양한 컴포넌트 이벤트 처리 – 텍스트 입력 받기 및 처리
import java.awt.*;
import java.awt.event.*;
class FrameEvent extends Frame implements
ActionListener {
TextField txtContent;
TextArea txtState;
Button
btnAppend;
public FrameEvent( ) {//생성자
setLayout(new BorderLayout( ));
txtContent=new TextField(20);
txtState = new TextArea( );
btnAppend = new Button("추 가" );
this.add(txtContent, BorderLayout.NORTH);
this.add(txtState, BorderLayout.CENTER);
this.add(btnAppend, BorderLayout.SOUTH);
btnAppend.addActionListener(this);
setSize(400,300);
setVisible(true);
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent e){
if(txtContent.getText() != ""){
txtState.append(txtContent.getText()+"\n");
txtContent.setText("");
}
}
}
public class ComTest02{
public static void main(String[] args) {
new FrameEvent( );
}
}
다양한 컴포넌트 이벤트 처리 – 체크박스 처리
import java.awt.*;
import java.awt.event.*;
class FrameEvent extends Frame implements ItemListener {
Panel
p;
Checkbox cb1, cb2, cb3;
addWindowListener(new WindowAdapter( ){
TextArea ta;
public void windowClosing(WindowEvent e) {
public FrameEvent( ) {//생성자
dispose();
setLayout(new BorderLayout( ));
System.exit(0);
//패널 객체 생성
}
p=new Panel( );
}
cb1 = new Checkbox("빨간 색");
);
cb2 = new Checkbox("파란 색");
}
cb3 = new Checkbox("초록 색");
p.add(cb1);
public void itemStateChanged(ItemEvent e){
p.add(cb2);
String strState="해제";
p.add(cb3);
if(e.getStateChange( ) == ItemEvent.SELECTED)
strState="선택";
this.add(p, BorderLayout.NORTH);
ta.append(e.getItem( ) +"이 " + strState + "되었습니다.\n");
}
ta=new TextArea( );
}
this.add(ta, BorderLayout.CENTER);
public class ComTest03{
cb1.addItemListener(this);
public static void main(String[] args) {
cb2.addItemListener(this);
new FrameEvent( );
cb3.addItemListener(this);
}
setSize(400,200);
}
setVisible(true);
다양한 컴포넌트 이벤트 처리 – 라디오버튼 처리
import java.awt.*;
import java.awt.event.*;
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
});
class FrameEvent extends Frame implements
ItemListener {
Checkbox cb1, cb2, cb3;
CheckboxGroup colorGrp;
public FrameEvent( ) {
setLayout(new FlowLayout( ));
colorGrp=new CheckboxGroup( );
cb1 = new Checkbox("빨간 색", colorGrp, false);
cb2 = new Checkbox("초록 색", colorGrp, false);
cb3 = new Checkbox("파란 색", colorGrp, false);
this.add(cb1);
this.add(cb2);
this.add(cb3);
cb1.addItemListener(this);
cb2.addItemListener(this);
cb3.addItemListener(this);
setSize(400,200);
setVisible(true);
}
public void itemStateChanged(ItemEvent e){
Object obj =e.getItem( );
if(obj=="빨간 색")
this.setBackground(Color.red);
else if(obj=="초록 색")
this.setBackground(Color.green);
else if(obj=="파란 색")
this.setBackground(Color.blue);
}
}
public class ComTest04{
public static void main(String[] args) {
new FrameEvent( );
}
}
다양한 컴포넌트 이벤트 처리 – 콤보상자 처리
import java.awt.*;
import java.awt.event.*;
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
} );
class FrameEvent extends Frame implements
ItemListener {
Label la;
Choice c;
TextArea ta;
public FrameEvent( ) {
setLayout(new BorderLayout( ));
c=new Choice( );
c.addItem("사과");
c.addItem("바나나");
c.addItem("딸기");
c.addItem("포도");
ta = new TextArea( );
this.add(c, BorderLayout.NORTH);
this.add(ta, BorderLayout.CENTER);
c.addItemListener(this);
setSize(400,200);
setVisible(true);
}
public void itemStateChanged(ItemEvent e){
if(e.getStateChange() == ItemEvent.SELECTED)
ta.append(e.getItem() + "가(이) 선택되었습니다.\n");
}
}
public class ComTest05{
public static void main(String[] args) {
new FrameEvent( );
}
다양한 컴포넌트 이벤트 처리 – 리스트박스 처리
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
} );
}
import java.awt.*;
import java.awt.event.*;
class FrameEvent extends Frame implements
ItemListener {
List li;
TextArea ta;
public FrameEvent( ) {
li=new List( );
li.addItem("사과");
li.addItem("바나나");
li.addItem("딸기");
li.addItem("포도");
public void itemStateChanged(ItemEvent e){
List li=(List)e.getSource( );
String item=li.getSelectedItem( );
ta.append(item + "가(이) 선택되었습니다.\n");
}
}
ta=new TextArea( );
this.add(li, BorderLayout.NORTH);
this.add(ta, BorderLayout.CENTER);
li.addItemListener(this);
setSize(400,200);
setVisible(true);
public class ComTest06{
public static void main(String[] args) {
new FrameEvent( );
}
}
다양한 컴포넌트 이벤트 처리 – 리스트박스 다중 선택처
리
import java.awt.*;
import java.awt.event.*;
public void itemStateChanged(ItemEvent e){
String []item;
String total="";
int i;
List li=(List)e.getSource();
item=li.getSelectedItems( );
for(i=0; i<item.length-1; i++)
total = total + item[i] + ", ";
total = total + item[i];
tf.setText(total + "가(이) 선택되었습니다.");
}
class FrameEvent extends Frame implements ItemListener {
List li;
TextField tf;
public FrameEvent( ) {
li=new List(6, true);
li.addItem("사과"); li.addItem("바나나"); li.addItem("딸기");
li.addItem("포도"); li.addItem("멜론");
li.addItem("배");
li.addItem("복숭아"); li.addItem("감");
li.addItem("수박");
tf = new TextField( );
this.add(li, BorderLayout.NORTH);
this.add(tf, BorderLayout.CENTER);
li.addItemListener(this);
setSize(400,150);
setVisible(true);
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
} );
}
}
public class ComTest07{
public static void main(String[] args) {
new FrameEvent( );
}
}
다양한 컴포넌트 이벤트 처리 – 스크롤바 처리
import java.awt.*;
import java.awt.event.*;
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
} );
}
class FrameEvent extends Frame implements
AdjustmentListener {
Scrollbar sc;
TextArea ta;
public FrameEvent( ) {
setLayout(new BorderLayout( ));
public void adjustmentValueChanged(AdjustmentEvent e) {
sc=new Scrollbar(Scrollbar.HORIZONTAL, 0, 5, 0, 100);
ta.append(e.getAdjustmentType( ) + ", " + e.getValue( ) + "\n");
ta=new TextArea( );
}
this.add(sc, BorderLayout.NORTH);
}
this.add(ta, BorderLayout.CENTER);
sc.addAdjustmentListener(this);
public class ComTest08{
setSize(400,150);
public static void main(String[] args) {
setVisible(true);
new FrameEvent( );
}
}
다양한 컴포넌트 이벤트 처리 – 캔버스 등록
import java.awt.*;
import java.awt.event.*;
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
}
);
class FrameEvent extends Frame {
Canvas cv;
public FrameEvent( ) {
setLayout(new FlowLayout( ));
cv=new Canvas( );
cv.setBackground(Color.blue);
cv.setSize(100, 50);
add(cv);
setSize(400,150);
setVisible(true);
}
}
public class ComTest09{
public static void main(String[] args) {
new FrameEvent( );
}
}
다양한 컴포넌트 이벤트 처리 – 메뉴 등록 및 처리
import java.awt.*;
import java.awt.event.*;
mitem.addActionListener(this);
setSize(400,150);
setVisible(true);
class FrameEvent extends Frame implements
ActionListener {
Canvas cv;
MenuBar mb;
public FrameEvent( ) {
cv=new Canvas( );
cv.setBackground(Color.black);
add(cv);
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
}
);
mb=new MenuBar();
setMenuBar(mb);
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand( ) == "빨간색")
cv.setBackground(Color.red);
else if(e.getActionCommand( ) == "초록색")
cv.setBackground(Color.green);
else if(e.getActionCommand( ) == "파란색")
cv.setBackground(Color.blue);
}
Menu colorMenu=new Menu("색상");
mb.add(colorMenu);
MenuItem mitem;
mitem=new MenuItem("빨간색");
colorMenu.add(mitem);
mitem.addActionListener(this);
}
mitem=new MenuItem("초록색");
colorMenu.add(mitem);
mitem.addActionListener(this);
mitem=new MenuItem("파란색");
colorMenu.add(mitem);
public class ComTest10{
public static void main(String[] args) {
new FrameEvent( );
}
}
입력관련 이벤트 - KeyListener
import java.awt.*;
import java.awt.event.*;
class FrameEvent extends Frame implements KeyListener {
TextArea ta ;
TextField txt ;
public FrameEvent(){
txt = new TextField();
txt.addKeyListener(this);
ta=new TextArea();
add("Center",ta );
add("North", txt);
setSize(200,200);
public void keyPressed(KeyEvent e){
setVisible(true);
ta.appendText( e.getKeyChar() +" 가 눌림\n");
}
}
public void keyTyped(KeyEvent e){
public void keyReleased(KeyEvent e){
ta.appendText( e.getKeyChar() +" 가 입력\n");
ta.appendText( e.getKeyChar() +" 를 놓았음\n");
if( e.getKeyChar() = 27 ) {
}
dispose();
}
System.exit(0);
}
class InputEventTest01{
}
public static void main(String [] args){
new FrameEvent( );
}
}
입력관련 이벤트 - MouseListener
import java.awt.*;
import java.awt.event.*;
class FrameEvent extends Frame implements MouseListener{
public FrameEvent(){
addMouseListener(this );
public void mousePressed(MouseEvent e){
setSize(300,300);
System.out.println("마우스 버튼을 누름");
setVisible(true);
}
public void mouseReleased(MouseEvent e){
addWindowListener(new WindowAdapter( ){
System.out.println("마우스 버튼을 놓음");
public void windowClosing(WindowEvent e) {
}
dispose();
public void mouseEntered(MouseEvent e){
System.exit(0);
System.out.println("마우스가 윈도우 안에 들어옴");
}
}
} );
public void mouseExited(MouseEvent e){
}
System.out.println("마우스가 윈도우 밖으로 나감");
public void mouseClicked(MouseEvent e){
}
System.out.println("마우스 버튼을 클릭함");
}
}
class InputEventTest02{
public static void main(String [] args){
new FrameEvent( );
}
}
입력관련 이벤트 - MouseMotionListener
import java.awt.*;
import java.awt.event.*;
class FrameEvent extends Frame implements MouseMotionListener {
Label info ;
public FrameEvent(){
info = new Label();
add("North", info);
addMouseMotionListener(this );
setSize(300,300);
setVisible(true);
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
public void mouseDragged(MouseEvent e){
System.exit(0);
info.setText(" 마우스 드래그 ");
}
}
} );
}
public void mouseMoved(MouseEvent e){
info.setText("X = "+e.getX()+" Y= "+e.getY());
}
}
class InputEventTest03{
public static void main(String [] args){
new FrameEvent( );
}
}
입력관련 이벤트 - TextListener
import java.awt.*;
import java.awt.event.*;
class FrameEvent extends Frame implements TextListener{
Label info ;
TextField txt ;
public FrameEvent(){
info = new Label( );
add("North", info);
txt = new TextField( );
add("South", txt);
txt.addTextListener(this);
setSize(300,100);
setVisible(true);
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
}
);
}
public void textValueChanged(TextEvent e){
info.setText( txt.getText() );
}
}
class InputEventTest04{
public static void main(String [] args){
new FrameEvent( );
}
}
입력관련 이벤트 – TextListener 2
import java.awt.*;
import java.awt.event.*;
class FrameEvent extends Frame {
TextArea ta ;
TextField txt;
public FrameEvent(){
ta=new TextArea();
add("Center", ta);
txt = new TextField();
add("North", txt);
txt.addKeyListener(new KeyAdapter() {
// 입력된 키의 종류 판별, 키가 눌렸을때 발생
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==KeyEvent.VK_UP)
ta.appendText( "위 방향키가 눌림\n");
else if(e.getKeyCode()==KeyEvent.VK_DOWN)
ta.appendText( "아래 방향키가 눌림\n");
else if(e.getKeyCode()==KeyEvent.VK_LEFT)
ta.appendText( "왼쪽 방향키가 눌림\n");
else if(e.getKeyCode()==KeyEvent.VK_RIGHT)
ta.appendText( "오른쪽 방향키가 눌림\n");
else
ta.appendText( e.getKeyChar() +" 가 눌림\n");
}
});
setSize(200,200);
setVisible(true);
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
});
}
}
class InputEventTest05{
public static void main(String [] args){
new FrameEvent( );
}
}
Dialog 클래스
import java.awt.*;
import java.awt.event.*;
class FrameEvent extends Frame implements
ActionListener{
Button btn ;
public FrameEvent( ) {
setLayout(new FlowLayout());
btn = new Button("대화상자 출력");
add(btn);
btn.addActionListener(this);
setSize(300,200);
setVisible(true);
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
} );
}
public void actionPerformed(ActionEvent e) {
MyDialog dlg=new MyDialog(this);
dlg.show();
}
}
class MyDialog extends Dialog implements
ActionListener{
Button yes, no ;
Panel pan;
public MyDialog(Frame parent){
super(parent, "나의 첫 대화상자");
add("North", new Label("안녕하세요"));
pan = new Panel();
pan.setLayout(new FlowLayout());
yes = new Button("예");
pan.add("West", yes);
yes.addActionListener(this);
no = new Button("아니오");
pan.add("East", no);
no.addActionListener(this);
add("South",pan);
setSize(300,200);
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
}
} );
}
public void actionPerformed(ActionEvent e){
dispose(); }
}
public class DialogTest02{
public static void main(String[] args) {
new FrameEvent( );
}
}
FileDialog 클래스
import java.awt.*;
import java.awt.event.*;
class FrameEvent extends Frame implements ActionListener{
Button btn ;
Label lbl;
public FrameEvent( ) {
lbl = new Label();
btn = new Button("대화상자 출력");
add("North",btn);
add("Center",lbl);
btn.addActionListener(this);
setSize(300,200);
setVisible(true);
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
} );
public void actionPerformed(ActionEvent e) {
}
FileDialog dlg = new FileDialog(this,"파일 다이얼로그",FileDialog.LOAD);
dlg.setSize(300,200);
dlg.show();
lbl.setText(dlg.getDirectory()+dlg.getFile());
}
}
public class DialogTest03{
public static void main(String[] args) {
new FrameEvent( );
}
}
그래픽 – paint 머서드
import java.awt.*;
import java.awt.event.*;
class GraphicFrame extends Frame{
//paint 메서드 오버라이딩
public void paint(Graphics g){
g.drawString("Hello World", 10, 60);
}
public GraphicFrame ( ){
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}});
}
}
public class GraphicTest00{
public static void main (String args[]){
GraphicFrame f = new GraphicFrame();
f.setSize(270,150);
f.setVisible(true);
}
}
그래픽 – Font 클래스
import java.awt.*;
import java.awt.event.*;
class GraphicFrame extends Frame{
Font f;
public void paint(Graphics g){
g.drawString("글꼴체가 변경되나요?", 10, 60);
f = new Font("궁서체", Font.BOLD, 20);
g.setFont(f);
g.drawString("글꼴체가 변경되었네요?", 10, 100);
}
public GraphicFrame ( ){
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}});
}
}
public class GraphicTest01{
public static void main (String args[]){
GraphicFrame f = new GraphicFrame();
f.setSize(270,150);
f.setVisible(true);
}
}
그래픽 – Color 클래스
import java.awt.*;
import java.awt.event.*;
class GraphicFrame extends Frame{
Color redColor;
//색상을 저장하는 객체 변수 선언
public void paint(Graphics g){
redColor=new Color(255, 0, 0);
//빨간색 객체 생성
g.setColor(redColor);
//빨간색을 지정한 후
g.drawString("빨간색 글자", 10, 50); //텍스트 출력
g.setColor(Color.GREEN);
//초록색을 지정한 후
g.drawString("초록색 글자", 10, 80); //텍스트 출력
g.setColor(Color.yellow);
//노란색을 지정한 후
g.drawString("노란색 글자", 10, 110); //텍스트 출력
}
public GraphicFrame ( ){
setBackground(new Color(0,0,0));
//프레임의 배경색을 검정색으로 지정
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}});
}
}
public class GraphicTest02{
public static void main (String args[]){
GraphicFrame f = new GraphicFrame();
f.setSize(270,150);
f.setVisible(true);
}
}
그래픽 – 도형 그리기
import java.awt.*;
import java.awt.event.*;
class GraphicFrame extends Frame{
Color redColor;
public void paint(Graphics g){
redColor=new Color(255, 0, 0);
g.setColor(redColor);
g.drawRect(10, 30, 40, 40);
g.fillOval(70, 30, 40, 40);
int x[]=new int[]{10, 30, 50, 40, 20};
int y[]=new int[]{107, 90, 107, 130, 130};
g.drawPolygon(x, y, x.length);
g.drawRoundRect(70, 90, 40, 40, 10, 10);
g.drawLine(150, 50, 200, 100);
g.drawLine(200, 50, 150, 100);
}
public GraphicFrame ( ){
addWindowListener(new WindowAdapter( ){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}});
}
}
public class GraphicTest03{
public static void main (String args[]){
GraphicFrame f = new GraphicFrame();
f.setSize(270,150);
f.setVisible(true);
}
}
Applet – 간단한 구조의 에플릿 프로그램
import java.applet.*;
import java.awt.*;
public class AppleExam extends Applet
{
public void paint(Graphics g)
{
g.drawString("Applet", 30, 30);
}
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<BODY>
<APPLET code="ThreadTest07.class" width="300"
height="300"></APPLET>
</BODY>
</HTML>
Applet - 주기
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class AppletExam01 extends Applet implements MouseListener
{
int x, y;
public void paint(Graphics g)
public void init(){
{
addMouseListener(this);
if(x != -1 || y != -1){
System.out.println("# init 메서드 수행");
String str;
}
str="마우스가 클릭된 위치 : "+ x + ","+y;
public void start(){
//System.out.println("# paint 메서드 수행");
x=-1; y=-1;
g.drawString(str, 30, 30);
repaint();
}
//System.out.println("# start 메서드 수행");
}
}
public void mouseClicked(MouseEvent e){
public void stop(){
x=e.getX();
System.out.println("# stop 메서드 수행");
y=e.getY();
}
repaint();
public void destroy(){
}
System.out.println("# destroy 메서드 수행");
public void mouseEntered(MouseEvent e) {
}
}
public void mouseExited(MouseEvent e){
}
public void mousePressed(MouseEvent e){
}
public void mouseReleased(MouseEvent e){
}
Thread – 상속에 의한 구현
//멀티스레드를 지원하는 클래스를 만들려면 java.lang.Thread 클래스의 상속
받아야 함
class ThreadExam extends Thread {
ThreadExam(String name){ //생성자에 스레드 이름이 전달인자로 넘어 옴
//ThreadExam의 상위 클래스인 Thread의 생성자( super)를 호출
super(name);//전달인자로 준 값이 스레드의 이름이 됨
}
public void run( ){
for(int num=1; num<=5; num++){
for(int k=1; k<100000000; k++);
//시간을 필요로 하는 작업을 위한 설
정
//스레드의 이름을 얻어 출력함
System.out.println(getName() + " : " + num);
}
}
}
class ThreadTest01{
public static void main (String args[]){
//스레드 클래스를 인스턴스화하여 독립된 스레드를 생성
ThreadExam t1=new ThreadExam("첫 번째 스레드");
ThreadExam t2=new ThreadExam("두 번째 스레드");
//start( ) 메소드를 호출하면 스레드 객체의 run( ) 메소드가 돌면서 스레드
가 실행
t1.start();
t2.start();
}
}
Thread – Runable 인터페이스 상속
//Runnable 인터페이스를 구현하는 클래스를 선언
class RunnableExam implements Runnable {
public void run( ){
for(int num=1; num<=5; num++){
//시간을 필요로 하는 작업
for(int k=1; k<100000000; k++);
//어떤 스레드가 수행중인지 확인하기 위해서 스레드의 이름을 얻어 와서 숫자와 함께 출력해 준다.
System.out.println(Thread.currentThread( ).getName( ) + " : " + num);
}
}
}
class ThreadTest03{
public static void main (String args[]){
//Runnable 인터페이스를 구현하는 클래스의 인스턴스를 생성
RunnableExam R1 = new RunnableExam();
RunnableExam R2 = new RunnableExam();
//스레드를 생성할 때 Runnable 인터페이스를 구현하는 클래스의 인스턴스를 매개변수로 넘겨줌
Thread t1=new Thread(R1, "첫 번째 스레드");
Thread t2=new Thread(R2, "두 번째 스레드");
t1.start();
t2.start();
}
}
Thread – Thread 활용
class RunnableExam implements Runnable {
int count=0;
//run( ) 실행을 언제 멈출 것인지를 결정하는 변수
int num =0;
//num이 count가 도달할 때까지 run( ) 메소드를 수행한다.
boolean timeOut=false; //run 메소드를 빠져 나가기 위한 변수
RunnableExam(int n){ //스레드 객체 생성할 때 넘겨준 전달인자를
count=n;
//count 변수에 저장하여 스레드를 언제까지 동작할 지 결정
}
public void run( ){
while( !timeOu t){
//timeOut이 true가 되면 run 메소드를 빠져 나간다.
try{
//스레드가 번갈아 가면서 차례대로 실행되도록 하기 위해서
Thread.sleep(100); //스레드를 일정시간 동안 대기 상태로 둔다.
}catch(InterruptedException e){
System.out.println(e);
}
num++;
//num 값을 계속 증가 시켜
Thread – Thread 활용
if(count<=num++) //count와 같은지 확인하여 num이 count에 도달하면
timeOut=true;
//while문을 벗어나기 위해서 timeOut에 true를 대입한다.
//스레드의 이름을 얻어 와서 스레드와 이름과 함께 변수 num 값을 출력
System.out.println(Thread.currentThread( ).getName( ) + " : " +num);
}
}
}
class ThreadTest04{
public static void main (String args[]){
RunnableExam R1 = new RunnableExam(12);
RunnableExam R2 = new RunnableExam(15);
RunnableExam R3 = new RunnableExam(10);
Thread t1=new Thread(R1, "첫 번째 스레드");
Thread t2=new Thread(R2, "두 번째 스레드");
Thread t3=new Thread(R3, "세 번째 스레드");
t1.start();
t2.start();
t3.start();
}
}
Thread – Frame에서 Thread 사용하기
import java.awt.*;
import java.awt.event.*;
class GraphicFrame extends Frame implements Runnable
{
int x=1;
public GraphicFrame(){
setBackground(new Color(0,0,0));
setSize(370, 150);
setVisible(true);
}
public void paint(Graphics g){
public void run(){
Dimension d;
while(true){
d=getSize();
try{
g.setColor(Color.yellow);
Thread.sleep(100);
g.drawString("클릭하세요 자바!!", x, d.height/2);
}catch(InterruptedException e){}
if(x>d.width)
repaint();
x=0;
x+=5;
}
}
}
}
class ThreadTest05{
public static void main(String[] args)
{
GraphicFrame f= new GraphicFrame();
Thread t1=new Thread(f);
t1.start();
}
}
Thread – Applet에서 Thread 사용
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class ThreadTest06 extends Applet
implements Runnable
{
Thread t1;
int x=100;
public void init(){
t1=new Thread(this);
t1.start();
}
public void run(){
while(true){
repaint();
x+=5;
try{
Thread.sleep(10);
}
catch(InterruptedException e){}
}
}
public void paint(Graphics g){
Dimension d;
d=getSize();
g.setColor(Color.blue);
g.fillOval(x, d.height*3/4, 20, 20);
if(x>d.width)
x=0;
}
};
Thread – Thread 우선 순위
class ThreadExam extends Thread
{
public ThreadExam(String str){
super(str);
}
public ThreadExam(String str, int priority ){
super(str);
setPriority(priority);
}
public void run(){
int i=0;
while(i++<5){
for(int k=1; k<100000000; k++);
System.out.println(getName() + ":" + getPriority());
}
}
};
class ThreadTest07
{
public static void main(String[] args)
{
Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
ThreadExam t1= new ThreadExam("첫번째 쓰레드");
ThreadExam t2= new ThreadExam("두번째 쓰레드", Thread.MAX_PRIORITY);
ThreadExam t3= new ThreadExam("세번째 쓰레드", Thread.MIN_PRIORITY);
System.out.println(Thread.currentThread());
t1.start();
t2.start();
t3.start();
}
}
Thread - 동기화
this.obj = obj ;
}
public void run(){
for(int i = 0 ; i < 5 ; i++){
try{
sleep(500);
}catch(InterruptedException e){}
class Atm { //Atm 계좌
// 은행 계좌 잔액
private int money ;
public Atm(int m){ // 생성자
money = m; //계좌 개설시 입금한 금액
}
synchronized void deposit(int amount, String name){
money += amount ;
System.out.println(name +": 입금 금액 : "+ amount);
}
if(flag){
obj.deposit((int)(Math.random()*10+2)*100, getName());
obj.getmoney();
}
else{
obj.withdraw((int)(Math.random()*10+2)*100, getName());
obj.getmoney();
}
flag = !flag ;
synchronized void withdraw(int amount, String name){
if( (money - amount) > 0 ) { // 출금 가능하면
money -= amount ;
System.out.println(name +": 출금 금액 : "+ amount);
}
}
else{
System.out.println(name +": 출금 못함 (잔액이 부족)"); }
}
}
class ThreadTest08 {
}
public static void main(String [] args){
Atm obj = new Atm(1000);
public void getmoney( ){
AtmUser user1 = new AtmUser(obj,"성윤정");
System.out.println("
계좌 잔액은:"+ money) ;
AtmUser user2 = new AtmUser(obj,"전수빈");
}
AtmUser user3 = new AtmUser(obj,"전원지");
}
class AtmUser extends Thread {
boolean flag = false ;
Atm obj ;
public AtmUser( Atm obj, String name){
super(name);
user1.start();
user2.start();
user3.start();
}
}
이미지 – Applet에서 이미지 출력
import java.applet.Applet;
import java.awt.*;
public class ImageExam01 extends Applet {
Image img01=null; //이미지 객체 변수 선언
public void init() {
//해당 이미지 파일을 로딩하여 이미지 객체 생성
img01=getImage(getDocumentBase( ),
"child.jpg");
}
public void paint(Graphics g){
//이미지를 화면에 출력
g.drawImage(img01, 0, 0, this);
}
}
<html>
<head>
<title></title>
</head>
<body>
<applet code="ImageExam01.class" width="1000" height="800"></applet>
</body>
</html>
이미지 – Application에서 이미지 출력
class ImageExam03 extends Frame{
Image []img;
String []filename;
int i;
ImageExam03(){
filename = new String[10];
img = new Image[10];
import java.awt.*;
for(int i=1; i<=10; i++){
import java.awt.event.*;
filename[i-1]="duke"+i+".gif";
img[i-1]=Toolkit.getDefaultToolkit().getImage(filename[i-1]);
class Test09_A{
public static void main(String[] args) }
{
setSize(950, 150);
new ImageExam03();
setVisible(true);
}
}
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dispose();
System.exit(0);
}
});
}
public void paint(Graphics g){
for(int i=1; i<=10; i++)
g.drawImage(img[i-1], 90*(i-1)+30, 73, this);
}
}
이미지 - 애니메이션
import java.awt.*;
import java.awt.event.*;
class Test09_A03{
public static void main(String[] args) {
new ImageExam04();
}
}
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dispose();
System.exit(0);
}
});
}
class ImageExam04 extends Frame implements Runnable {
public void paint(Graphics g){
Image []img;
g.drawImage(img[index], 70, 70, this);
String []filename;
}
int i;
public void run(){
Thread th;
while(true){
int index = -1;
index++;
ImageExam04(){
if(index>=img.length)
filename = new String[10];
index=0;
img = new Image[10];
try{
for(int i=1; i<=10; i++){
th.sleep(100);
filename[i-1]="duke"+i+".gif";
repaint();
img[i-1]=Toolkit.getDefaultToolkit().getImage(filename[i-1]);
}catch(Exception e){}
}
}
th=new Thread(this);
}
th.start();
}
setSize(950, 150);
setVisible(true);
이미지 – 애니메이션(드블버퍼링)
import java.awt.*;
import java.awt.event.*;
public void update(Graphics g){
Dimension d;
d=getSize();
if(offImage==null){
offImage=createImage(d.width, d.height);
offGraphics=offImage.getGraphics();
}
offGraphics.setColor(getBackground());
offGraphics.fillRect(0, 0, d.width, d.height);
offGraphics.setColor(Color.black);
class Test09_A04{
public static void main(String[] args) {
new ImageExam05();
}
}
class ImageExam05 extends Frame implements Runnable {
Image []img;
String []filename;
int i;
Thread th;
int index = -1;
Image
offImage=null;
Graphics offGraphics=null;
ImageExam05(){
filename = new String[10];
img = new Image[10];
for(int i=1; i<=10; i++){
filename[i-1]="duke"+i+".gif";
img[i-1]=Toolkit.getDefaultToolkit().getImage(filename[i-1]);
}
th=new Thread(this);
th.start();
setSize(950, 150);
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dispose();
System.exit(0);
}
}); }
offGraphics.drawImage(img[index], 0, 0, null);
paint(g);
}
public void paint(Graphics g){
if(offImage != null)
g.drawImage(offImage, 70, 70, this);
}
public void run(){
while(true){
index++;
if(index>=img.length)
index=0;
try{
th.sleep(100);
repaint();
}catch(Exception e){}
} }}
예외 처리 – 0으로 나누기 에러
public class ExcepTest01 {
public static void main(String[] args) {
int a=10, b01=0, b02=2, c=10;
c = a / b02; //(1)
System.out.println(" c -> " + c);
c = a / b01; //(2)
System.out.println(" c -> " + c);
c = a / b02; //(3)
System.out.println(" c -> " + c);
System.out.println(" 정상 종료 " + c);
}
예외 처리 – if 문에 의한 예외 처리
public class ExcepTest02 {
public static void main(String[] args) {
int a=10, b01=0, b02=2, c=10;
if(b02==0) {
System.out.println("예외 상황이 발생하였습니다. ");
}
else{
c = a / b02; //(1)
System.out.println(" c -> " + c);
}
if(b01==0) {
System.out.println("예외 상황이 발생하였습니다. ");
}
else{
c = a / b01; //(2)
System.out.println(" c -> " + c);
}
if(b02==0) {
System.out.println("예외 상황이 발생하였습니다. ");
}
else{
c = a / b02; //(3)
System.out.println(" c -> " + c);
}
}
}
예외 처리 – try ~ catch 문에 의한 예회처리
public class ExcepTest03 {
public static void main(String[] args) {
int a=10, b01=0, b02=2, c=10;
System.out.println("try 구문 수행하기 전 c -->" + c);
try {
System.out.println("try 구문으로 들어옴");
System.out.println("나누기 연산하기 전 try 구문");
c = a / b02; //(1)
System.out.println(" (1) c -> " + c);
c = a / b01; //(2)
System.out.println(" (2) c -> " + c);
c = a / b02; //(3)
System.out.println(" (3) c -> " + c);
}
catch(Exception e) {
System.out.println("예외가 발생하여 Exception 객체가 잡음->" + e);
}//예외처리 끝
System.out.println("try 구문을 수행한 후 c-->" + c);
}
}
예외 처리 – try ~ catch 문에 의한 예회처리 2
public class ExcepTest04 {
public static void main(String[] args) {
int a=10, b01=0, b02=2, c=10;
System.out.println("try 구문 수행하기 전 c -->" + c);
try {
System.out.println("try 구문으로 들어옴");
System.out.println("나누기 연산하기 전 try 구문");
c = a / b02; //(1)
System.out.println(" (1) c -> " + c);
c = a / b01; //(2)
System.out.println(" (2) c -> " + c);
c = a / b02; //(3)
System.out.println(" (3) c -> " + c);
}
//하위 클래스로 특수한 사항에 대한 예외를 처리하는 클래스를 우선적으로 기술함
catch(ArithmeticException e) {
System.out.println("예외가 발생하여 ArithmeticException객체가 잡음->" + e);
}
//반면 위에 기술된 catch 구문에서 처리하지 못한 예외만 Exception 객체가 처리함
catch(Exception e) {
System.out.println("예외가 발생하여 Exception 객체가 잡음->" + e);
}
System.out.println("try 구문을 수행한 후 c-->" + c);
}
}
예외 처리 – finally 문
public class ExcepTest05 {
public static void main(String[] args) {
int a=10, b01=0, b02=2, c=10;
System.out.println("try 구문 수행하기 전 c -->" + c);
try {
System.out.println("try 구문으로 들어옴");
System.out.println("나누기 연산하기 전 try 구문");
c = a / b02; //(1)
System.out.println(" (1) c -> " + c);
c = a / b01; //(2)
System.out.println(" (2) c -> " + c);
c = a / b02; //(3)
System.out.println(" (3) c -> " + c);
}
catch(ArithmeticException e) {
System.out.println("예외가 발생하여 ArithmeticException객체가 잡음->" + e);
}
catch(Exception e) {
System.out.println("예외가 발생하여 Exception 객체가 잡음->" + e);
}
finally{
System.out.println("try/catch 구문에 대한 정리 작업 c-->" + c);
}//예외처리 끝
System.out.println("try 구문을 수행한 후 c-->" + c);
}
}
예외 – 인위적 예외 발생
public class ThrowTest02{
public static void exp(int ptr){
if(ptr == 0)
throw new NullPointerException(); //프로그래머가 예외 발생시킴
}
public static void main(String[] args) {
exp(0);
}
}
예외 처리 – 인위적, 사용자 정의 예외 처리
class UserException extends Exception {
public UserException(String str){
super(str);
}
}
class ExcepTest09 {
public static void main(String [] args){
try{
int a = -11 ;
if( a <= 0){
//사용자가 정의한 예외를 인위적으로 발생시킴
throw new UserException("양수가 아닙니다.");
}
}
catch(UserException e){
System.out.println( e.getMessage());
}
}
}
입출력 – 기본 입력
public class IOTest00{
public static void main(String[] args) throws Exception {
int data=0;
System.out.println("문자를 입력하세요. 끝내려면 [Ctrl]+Z를 누르세요.");
data = System.in.read();
while(data != -1){
System.out.print((char)data);
data = System.in.read();
}
}
}
입출력 – 기본 입력 2
import java.io.*;
public class IOTest01 {
public static void main(String[] args) {
int data=0;
System.out.println("문자를 입력하세요. 끝내려면 [Ctrl]+Z를 누르세요.");
try{
InputStream myIn=System.in;
while( (data = myIn.read( )) != -1)
System.out.print((char)data);
}catch ( IOException e ){
e.printStackTrace();
}
}
}
입출력 – 기본 출력
import java.io.*;
public class IOTest0A{
public static void main(String[] args) throws Exception {
int data=0;
System.out.println("문자를 입력하세요. 끝내려면 [Ctrl]+Z를 누르세요.");
OutputStream myOut = System.out;
while((data = System.in.read()) != -1){
myOut.write(data);
}
}
}
입출력 – File 객체를 이용한 파일 정보 출력
import java.io.*;
import java.util.*; //Date
class FileTest01 {
public static void main(String [] args) throws Exception {
File file=null;
//File 객체 변수 선언
byte []byteFileName=new byte[100];
//파일 이름을 입력받기 위한 byte 배열 선언
String fileName;
//byte 배열에 읽어온 파일 이름을 String으로 변환하여 저장
System.out.print("파일명 -> ");
//키보드에서 입력받은 값을 byteFileName에 저장, read(byte[] b)가 호출된 것임
System.in.read(byteFileName);
//키보드에서 입력받은 값을 fileName 변수에 저장, 이때 공백이 생길 수 있으므로 trim으로 제거
fileName=new String(byteFileName).trim();
file = new File(fileName);
//File 클래스의 인스턴스를 생성
System.out.println( fileName + " 파일 상세 정보 *****" );
System.out.println("절대 경로 : " + file.getAbsolutePath());
System.out.println("표준 경로 : " + file.getCanonicalPath());
System.out.println("생성일 : " + new Date(file.lastModified()));
System.out.println("파일 크기 : " + file.length() );
System.out.println("읽기 속성 : " + file.canRead() );
System.out.println("쓰기 속성 : " + file.canWrite() );
System.out.println("파일 경로 : " + file.getParent() );
System.out.println("숨김 속성 : " + file.isHidden() );
}
}
입출력 – 파일 내용 출력
import java.io.*;
class FileType01{
public static void main(String[] args) {
int data=0;
int size=0;
if (args.length <1){
System.out.println("USAGE : java FileType01 file_name");
System.exit(0);
}
String path=args[0];
try{
File f=new File(path);
FileInputStream fis=new FileInputStream(f);
//FileInputStream fis=new FileInputStream(path);
while((data=fis.read()) != -1){
System.out.write((char)data);
size++;
}
System.out.println("\n파일크기 : "+size+" byte");
}
catch(FileNotFoundException fe) {
fe.printStackTrace();
}
catch(IOException ie){
ie.printStackTrace();
}
}
}
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )