RMI(Remote Method Invocation)

Similar documents
PowerPoint Presentation

1

PowerPoint 프레젠테이션

PowerPoint Presentation

q 이장에서다룰내용 1 객체지향프로그래밍의이해 2 객체지향언어 : 자바 2

02 C h a p t e r Java

Microsoft PowerPoint - 04-UDP Programming.ppt

PowerPoint Presentation

07 자바의 다양한 클래스.key

JAVA PROGRAMMING 실습 08.다형성

제11장 프로세스와 쓰레드

PowerPoint Presentation

PowerPoint 프레젠테이션

gnu-lee-oop-kor-lec06-3-chap7

슬라이드 1

Microsoft PowerPoint 자바-기본문법(Ch2).pptx

JAVA PROGRAMMING 실습 09. 예외처리

Microsoft PowerPoint - CSharp-10-예외처리

예제 2) Test.java class A intvar= 10; void method() class B extends A intvar= 20; 1"); void method() 2"); void method1() public class Test 3"); args) A

<4D F736F F F696E74202D20C1A63038C0E520C5ACB7A1BDBABFCD20B0B4C3BC4928B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

Microsoft PowerPoint - Supplement-03-TCP Programming.ppt [호환 모드]

Design Issues

12-file.key

PowerPoint 프레젠테이션

01-OOPConcepts(2).PDF

Microsoft PowerPoint - 2강

rmi_박준용_final.PDF

JVM 메모리구조

10.0pt1height.7depth.3width±â10.0pt1height.7depth.3widthÃÊ10.0pt1height.7depth.3widthÅë10.0pt1height.7depth.3width°è10.0pt1height.7depth.3widthÇÁ10.0pt1height.7depth.3width·Î10.0pt1height.7depth.3width±×10.0pt1height.7depth.3width·¡10.0pt1height.7depth.3width¹Ö pt1height.7depth.3widthŬ10.0pt1height.7depth.3width·¡10.0pt1height.7depth.3width½º, 10.0pt1height.7depth.3width°´10.0pt1height.7depth.3widthü, 10.0pt1height.7depth.3widthº¯10.0pt1height.7depth.3width¼ö, 10.0pt1height.7depth.3width¸Þ10.0pt1height.7depth.3width¼Ò10.0pt1height.7depth.3widthµå

Microsoft PowerPoint - 03-TCP Programming.ppt

PowerPoint 프레젠테이션

JAVA PROGRAMMING 실습 05. 객체의 활용

(Microsoft PowerPoint - java1-lecture11.ppt [\310\243\310\257 \270\360\265\345])

C# Programming Guide - Types

PowerPoint 프레젠테이션

Cluster management software

슬라이드 1

오버라이딩 (Overriding)

PowerPoint Presentation

PowerPoint 프레젠테이션

iii. Design Tab 을 Click 하여 WindowBuilder 가자동으로생성한 GUI 프로그래밍환경을확인한다.

No Slide Title

PowerPoint Presentation

JAVA 프로그래밍실습 실습 1) 실습목표 - 메소드개념이해하기 - 매개변수이해하기 - 새메소드만들기 - Math 클래스의기존메소드이용하기 ( ) 문제 - 직사각형모양의땅이있다. 이땅의둘레, 면적과대각

PowerPoint Presentation

JUNIT 실습및발표

PowerPoint 프레젠테이션

PowerPoint Presentation

Microsoft PowerPoint - Lect04.pptx

쉽게 풀어쓴 C 프로그래밍

PowerPoint Presentation

쉽게 풀어쓴 C 프로그래밍

Network Programming

PowerPoint Presentation

PowerPoint 프레젠테이션

Semantic Consistency in Information Exchange

ilist.add(new Integer(1))과 같이 사용하지 않고 ilist.add(1)과 같이 사용한 것은 자바 5.0에 추가된 기본 자료형과 해당 객체 자료 형과의 오토박싱/언박싱 기능을 사용한 것으로 오토박싱이란 자바 컴파일러가 객체를 요구하는 곳에 기본 자료형

예외 예외정의예외발생예외처리예외전파 단정 단정의선언 단정조건검사옵션 2

Microsoft PowerPoint - lec2.ppt

PowerPoint Presentation

쉽게 풀어쓴 C 프로그래밍

슬라이드 1

JAVA PROGRAMMING 실습 02. 표준 입출력

비긴쿡-자바 00앞부속

JAVA PROGRAMMING 실습 02. 표준 입출력

10장.key

4장.문장

PowerPoint 프레젠테이션

untitled

쉽게 풀어쓴 C 프로그래밍

PowerPoint 프레젠테이션

PowerPoint Presentation

PowerPoint 프레젠테이션

5장.key

(Microsoft PowerPoint - java2-lecture3.ppt [\310\243\310\257 \270\360\265\345])

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx

Connection 8 22 UniSQLConnection / / 9 3 UniSQL OID SET

교육자료

PowerPoint Presentation

Chap12

1. 자바프로그램기초 및개발환경 2 장 & 3 장. 자바개발도구 충남대학교 컴퓨터공학과

PowerPoint Presentation

Microsoft PowerPoint - RMI.ppt

PowerPoint Template

Microsoft PowerPoint - Chapter 6.ppt

9장.예외와 단정

Microsoft PowerPoint 장강의노트.ppt

Microsoft PowerPoint - 3ÀÏ°_º¯¼ö¿Í »ó¼ö.ppt

JMF3_심빈구.PDF

Microsoft PowerPoint - chap02-C프로그램시작하기.pptx

파일로입출력하기II - 파일출력클래스중에는데이터를일정한형태로출력하는기능을가지고있다. - PrintWriter와 PrintStream을사용해서원하는형태로출력할수있다. - PrintStream은구버전으로가능하면 PrintWriter 클래스를사용한다. PrintWriter

6주차.key

C++ Programming

<4D F736F F F696E74202D20C1A63139C0E520B9E8C4A120B0FCB8AEC0DA28B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

Microsoft PowerPoint - additional08.ppt [호환 모드]

<4D F736F F F696E74202D20C1A63234C0E520C0D4C3E2B7C228B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

Cluster management software

작성자 : 김성박\(삼성 SDS 멀티캠퍼스 전임강사\)

11 템플릿적용 - Java Program Performance Tuning (김명호기술이사)

Transcription:

Java SE Programming

Module Overview 1. Getting Stared 2. Object-Oriented Programming 3. Identifiers, Keywords, and Data Types 4. Expressions and Flow Control 5. Array 6. Inheritance 7. Advanced Class Features 8. Exceptions 9. Collection API 10. AWT

Module Overview 11. GUI Event Handling 12. Threads 13. Advanced I/O Streams 14. Networking

1. Getting Stared 미국 Sun Microsystems 사에서개발한객체지향프로그래밍언어 1995 년 5 월, Sun World 에서공식발표 1996 년 1 월, JDK1.0 발표 객체지향언어 (Object Oriented Language) 60 년말 Simula 언어에서발전 처음엔 oak 라는언어로불림 : 가전제품의소형칩개발을위해서만들어진언어. C++ 를문법을기본으로개발 Java 이전에객체지향언어로가장범용적인언어 1983년경, AT&T연구소의 Bjarne Stroustrup이개발 언어에객체지향특성확장

1. Getting Stared : 자바프로그램의동작방식 자바프로그래밍은컴파일과정과인터프리터과정둘다거쳐야한다. 1. 컴파일단계 : ~.java ~.class 2. 실행단계 : Class File Loader -> Vreifier -> Interpreter -> Runtime.java Javac.exe.java Java.exe

1. Getting Stared : 자바가상머신 (JVM). -JVM 은바이트코드만인식할수있다 - OS 별로각각다운로드해야한다 - 컴퓨터의 OS 위에탑재되고컴파일된클래스파일들은이위에서실행된다 자바프로그램 자바 API 자바가상머신 자바언어 자바플랫폼 다양한하드웨어플랫폼

1. Getting Stared : 플랫폼독립성 Write Once Run Anywhere!!.

1. Getting Stared : 기본적인세팅작업 1. www.oracle.com 에가서 JDK6.0 버전을다운로드한다. 2. JDK 를디폴트로설치한다 3. 편집툴설치 - 우선 Edit Plus 3.0 버전을설치해서설정까지잡아준다 - 추후에 Eclipse 파일을다운받는다. 4. JDK6.0 이설치되었다면자바홈과패스를환경변수에서잡아준다 5. 설치가잘되었는지간단한소스돌려서확인 : 이때콘솔창으로도확인!

1. Getting Stared : # 첫번째실습 : HelloJAVA <HelloJAVA.java 소스코드작성 > 1. Editor를사용하되 Copy 하지말고,. 오른쪽상단의소스코드를작성하여 HelloJAVA.java 로저장. 2. 컴파일 : 명령프롬프트를실행하여소스코드가저장된디렉토리로이동 > javac HelloJAVA.java 3. 실행 : 소스가저장된디렉토리 > java HelloJAVA } class HelloJAVA{ public static void main(string[]args){ System.out.println( HelloJAVA! ); }

1. Getting Stared : # HelloJAVA 소스에대한설명 class HelloJAVA{. public static void main(string[] args) } { } System.out.println( Hello JAVA! ); Class 라는키워드뒤에클래스이름을지정 클래스이름은대문자로시작하는것이관례 일반적으로소스코드파일의이름과클래스이름이동일하게함 Main 함수를기점으로모든프로그램이실행됨 System.out.println 메쏘드는표준출력으로명시된문자열을화면에출력하는역할을함

2. Object-Oriented Programming : merit 코드의재사용성이높다. - 새로운코드를작성할때기존의코드를이용해서쉽게작성할수있다. 코드의관리가쉬워졌다. - 코드간의관계를맺어줌으로써보다적은노력으로코드변경이가능하다. 신뢰성이높은프로그램의개발을가능하게한다. - 제어자와메서드를이용해서데이터를보호하고, 코드의중복을제거하여코드의불일치로인한오류를방지할수있다.

2. Object-Oriented Programming: 클래스와객체 클래스 객체를만들어내기위한하나의설계도. 클래스는객체를생성하는데사용되는일종의틀이다. 속성과행위로구성되어진틀. 객체 실제로존재하는것. 사물또는개념. 일반적인클래스의틀에서실질적인값을넣을수있다. 메모리에올라가서사용되는것. 클래스제품설계도 TV설계도붕어빵기계 객체제품 TV 붕어빵

2. Object-Oriented Programming: 클래스와객체 객체는속성과기능으로이루어져있다. - 객체는속성과기능의집합이며, 속성과기능을객체의멤버 (member, 구성요소 ) 라고한다. 속성은변수로, 기능은메서드로정의한다. - 클래스를정의할때객체의속성은변수로, 기능은메서드로정의한다. class Tv { 속성 크기, 길이, 높이, 색상, 볼륨, 채널등 변수 String color; // 색깔 boolean power; // 전원상태 (on/off) int channel; // 채널 기능 켜기, 끄기, 볼륨높이기, 볼륨낮추기, 채널높이기등 메서드 void power() { power =!power; } // 전원 on/off void channelup( channel++;) // 채널높이기 void channeldown {channel--;} // 채널낮추기 }

2. Object-Oriented Programming: 클래스와객체 클래스선언하기 Syntext: <modifier> class < 클래스이름 > { 변수선언 ; 메소드정의부분 { } } 예 : public class Person{ int age; public void setage{ int a){ age = a; } }

2. Object-Oriented Programming: 클래스와객체 멤버변수선언하기 Syntax of an attribute: [Access Modifier] 데이터타입 + 변수명 ; Examples: public class Foo { public int x; private float y = 10.0 ; String name = 홍길동 "; }

2. Object-Oriented Programming: 변수종류 선언위치에따라변수의종류는달라진다 변수의선언위치가변수의종류와범위 (scope) 을결정한다 변수의종류선언위치생성시기 클래스변수 인스턴스변수 클래스영역 클래스가메모리에올라갈때 인스턴스생성시 지역변수메서드영역변수선언문수행시

2. Object-Oriented Programming: 변수종류 멤버변수 - 각인스턴스의개별적인저장공간. 인스턴스마다다른값저장가능 - 인스턴스생성후, 참조변수. 인스턴스변수명 으로접근 - 인스턴스를생성할때생성되고, 참조변수가없을때가비지컬렉터에의해자동제거됨 로컬변수 - 메서드내에선언되며, 메서드의종료와함께소멸 - 조건문, 반복문의블럭 {} 내에선언된지역변수는블럭을벗어나면소멸

2. Object-Oriented Programming: 클래스와객체 메소드선언하기 Syntax of a method: <modifier> 리턴타입 + 메소드이름 (< 인자값 >*) { // 코드블락 } 예 : public class Thing { private int x; public int getx() { return x; } }

2. Object-Oriented Programming: 클래스와객체 Accessing Object Members 1. New 라는키워드를사용해서객체를생성 2. 레퍼런스변수를이용해서멤버에접근 : < 레퍼런스변수 >.<member> Examples: Person p = new Person(); p.age = 33; p.name = 홍길동 ; p.getinfo();

2. Object-Oriented Programming: 클래스와객체 The Default Constructor - 모든클래스에반드시하나이상의생성자는있게마련이다. - 만약에어떤생성자도개발자가넣어주지않았다면컴파일러가디폴트생성자를자동적으로넣어준다 -new 라는키워드를통해서객체를생성할때마다생성자는호츨된다 - 생성자는디폴트생성자와 / 명시적생성자가있다 - 명시적생성자가하는일은객체변수초기화이다!!

2. Object-Oriented Programming: 클래스와객체 In Java, classes support three key features of OOP: -Encapsulation - inheritance - polymorphism

2. Object-Oriented Programming: 클래스와객체 Information Hiding The Problem: MyDate +day : int +month : int +year : int MyDate d = new MyDate() d.day = 32; // invalid day d.month = 2; d.day = 30; // plausible but wrong d.day = d.day + 1; // no check for wrap around

2. Object-Oriented Programming: 클래스와객체 The Solution: MyDate -day : int -month : int -year : int +getday() : int +getmonth() : int +getyear() : int +setday(int day) : void +setmonth(int month) : void +setyear(int year) : void MyDate d = new MyDate() d.setday(32); // invalid day, returns false d.setmonth(2); d.setday(30); // plausible but wrong, setday returns false d.setday(d.getday() + 1); // this will return false if wrap around

2. Object-Oriented Programming: 클래스와객체 Encapsulation Pattern 멤버변수는 private 메소드 (setxxx() / getxxx()) 는 public setxxx(){ 안에서조건을달아서검증괸데이터만멤버에세팅되도록한다

2. Object-Oriented Programming: 클래스와객체 package 와 import 1 패키지 (package) - 서로관련된클래스와인터페이스의묶음. - 패키지는물리적으로폴더, 디렉토리개념이다. - 패키지는서브패키지를가질수있으며,. 으로구분한다.( 계층구조 ) - 클래스의실제이름 (full name) 은패키지명이포함된것이다 - rt.jar는 Java API의기본클래스들을압축한파일 (JDK설치경로\jre\lib에위치 ) -자바에서제공되는가장기본적인클래스들은 java.lang 패키지에속해있으며디폴트로인식되어 import 하지않고써도된다 - 패키지는소스파일에첫번째문장 ( 주석제외 ) 으로단한번선언한다

2. Object-Oriented Programming: 클래스와객체 package 와 import 2. import문 - 특정패키지에들어있는클래스를가져올떄사용하는키워드 - java.lang패키지의클래스는 import하지않고도사용할수있다. - import문을사용하면클래스를사용할때패키지명을생략할수있다.

3. Identifiers, Keywords, and Data Types 식별자 (Identifier) 프로그래머가직접만들어줘야하는이름 예 : 변수명, 클래스명, 메쏘드명등 <Identifier 규칙 > 1. A~ Z, a ~ z, _, $ 사용할수있음단, 대소문자를구분함 2. 숫자는두번째문자부터나올수있다. 3. 키워드는식별자로사용할수없음

3. Identifiers, Keywords, and Data Types 예약어 (Keyword) 프로그래밍언어에미리정의된의미있는단어 예약어는식별자로사용하지않음

3. Identifiers, Keywords, and Data Types Data types 기본형 (Primitive type) - 8개 (boolean, char, byte, short, int, long, float, double ) - 실제값을저장 참조형 (Reference type) - 기본형을제외한나머지 (String, System 등 ) - 객체의주소를저장 (4 byte, 0x00000000~0xffffffff)

3. Identifiers, Keywords, and Data Types 기본형 (Primitive type) 정수형 정수값을저장하는데사용된다. byte, short, in,t long 논리형 true 와 false 중하나를값으로갖으며, 조건식과논리적계산에사용된다. 문자형 char ( 변수당하나의문자만을저장할수있다. Ex) A ) 실수형 float 와 double 이있다. 소수점을가지는값을저장할떄사용

Identifiers, Keywords, and Data Types 자료형키워드크기표현범위사용예 논리형 boolean 1bit true OR false(0 과 1 이아니다 ) boolean isfun = true; 문자형 char 2byte 0~65,535 char c = f ; byte 1byte -128 ~ 127 byte b = 89; short 2byte -32,768 ~ 32,767 short s = 32760; 정수형 int 4byte -2147483648:2147483647 int x = 59; int z = x; long 8byte long big = 3456789; 실수형 float 4byte -3.4E38 ~ 3.4E38 float f = 32.5f double 8byte -1.7E308 ~ 1.7E308 double d = 23.34

Data Type: 기본형 / 참조형 ( 클래스타입 ) int myint = 19; myint 19 String mystr = new mystring(); 1 3 2 mystr 1 2 기본자료형 참조자료형 변수값실제값 Object 참조값 정의방식 Java 내부에이미정의됨클래스정의 생성방식 19", "3.14", "true" "new *

3. Identifiers, Keywords, and Data Types 변수 : 항상변하는값이저장되는공간, 값이아닌공간 1) 멤바변수 : int I; String s; 선언만하고초기화하지않아도됨기본값이있다. 클래스아래, 메소드바깥에서선언 2) 로컬변수 : int j=10; String str = null; 선언과동시에초기화필수기본값이없기때문이다메소드블록안에서사용됨 3) 상수 : 변하지않는값 final 키워드를붙이며변수명은전부다대문자로하는것이관례 HEAD_COUNT MAXIMUM_SIZE

3. Identifiers, Keywords, and Data Types Promotion Demotion byte short int long float double Promotion Demotion(Casting) long bigvalue = 99L; int squashed = bigvalue; // Wrong, needs a cast int squashed = (int) bigvalue; // OK int squashed = 99L; // Wrong, needs a cast int squashed = (int) 99L; // OK, but... int squashed = 99; // default integer literal

3. Identifiers, Keywords, and Data Types Promotion Demotion long bigval = 6; // 6 is an int type, OK int smallval = 99L; // 99L is a long, illegal double z = 12.414F; // 12.414F is float, OK float z1 = 12.414; // 12.414 is double, illegal

4. Expressions and Flow Control : if ~ else if ~ else if ( 조건문 )1 { statement or block; // 조건문이 true일때수행 } if ( 조건문2) { statement or block; } else if ( 조건문3) { statement or block; } else { // 이것도저것도아닐때이리로내려옴 조건이없다 statement or block; }

4. Flow Control : if ~ else if ~ else int count; count = getcount(); // 프로그램내에메소드가정의되었다는가정하에 if (count < 0) { System.out.println("Error: count value is negative."); } else if (count > getmaxcount()) { System.out.println("Error: count value is too big."); } else { System.out.println("There will be " + count + " people for lunch today."); }

4. Flow Control : switch switch ( 변수 ) { // 이때 byte,short,int char 데이터타입중하나가가능 case constant2 : statements break; case constant3: statements; break; default: //else와똑같은효력 statements; break; }

4. Flow Control : switch switch ( carmodel ) { case DELUXE: addairconditioning(); addradio(); addwheels(); addengine(); break; case STANDARD: addradio(); addwheels(); addengine(); break; }

4. Flow Control : for 문 for ( 초기화 ; 조건문 ; 증감문 ) { Code block; } Example: for (int i = 0; i < 10; i++) { System.out.println("Are you finished yet?"); } System.out.println("Finally!");

4. Flow Control : while 문 while ( 조건식 ) { statement or block; } Example: int i = 0; while (i < 10) { System.out.println("Are you finished yet?"); i++; } System.out.println("Done");

4. Flow Control : do ~ while 문 do { statement or block; } while (boolean test); Example: int i = 0; do { System.out.println("Are you finished yet?"); i++; } while (i < 10); System.out.println("Done");

5. Array Array 는같은데이타타입을가지는여러개의값들이 하나의변수를통해서한번에묶여질수있는것 기본형 Array / 참조형 Array Array도객체이다그래서 new 키워드를통해서생성한다 Re-Sizing이안된다 Array의사이즈를알수있는변수로는 length 가있다. 주로 for문과같이쓰인다.

5. Array : 배열의 3 단계 1. 선언 메모리상에참조변수를위한공간이잡힌다 int [ ] i; int i [ ]; String[ ] str; String str [ ]; Person[ ] p; Person p [ ];

5. Array : 배열의 3 단계 2. 배열생성. New 라는키워드를사용 / 사이즈를명시 i = new int [ 5 ] ; str = new String [ 3 ] ; p = new Person [ 2 ] ; Array 도 new 라는키워드를통해서생성된객체이기에메모리영역중 Heap 에저장됨

5. Array : 배열의 3 단계 3. 초기화.. 배열의각각의인덱스에해당하는값을세팅함 i[ 0 ] = 11; i[ 1 ] = 22; i[ 2 ] = 33; str[ 0 ] = 일등 ; str [ 1 ] = 이등 ; str[ 2 ] = 삼등 ; p[ 0 ] = new Person(); p[ 2 ] = new Person(); Primitive Type Array 와 Reference Type Array 는메모리상저장되는구조다름

5. Array : 배열의 3 단계 1 + 2+ 3 : 선언과생성돠초기화를동시에 int [ ] i = { 11, 22, 33 }; String[ ] str ={ 일등, 이등, 삼등, 사등, 오등 };

5. Array Copying Array The System.arraycopy() method: 1 //original array 2 int elements[] = { 1, 2, 3, 4, 5, 6 }; 3 4 // new larger array 5 int hold[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; 6 7 // copy all of the elements array to the hold 8 // array, starting with the 0th index 9 System.arraycopy(elements, 0, hold, 0, elements.length);

6. Inheritance : The is a Relationship The Employee class: Employee +name : String = "" +salary : double +birthdate : Date public class Employee { public String name = ""; public double salary; public Date birthdate; public String getdetails() {...} } +getdetails() : String

6. Inheritance : The isa Relationship The Manager class: Manager +name : String = "" +salary : double +birthdate : Date +department : String public class Manager { public String name = ""; public double salary; public Date birthdate; public String department; public String getdetails() {...} } +getdetails() : String

6. Inheritance : The is a Relationship Employee +name : String = "" +salary : double +birthdate : Date +getdetails() : String public class Employee { public String name = ""; public double salary; public Date birthdate; public String getdetails() {...} } Manager +department : String = "" public class Manager extends Employee { public String department = ""; }

6. Inheritance : Single Inheritance Employee +name : String = "" +salary : double +birthdate : Date +getdetails() : String Engineer Manager Secretary +department : String = ""

6. Inheritance : Single Inheritance 상속은부모가가진모든성질이자식에게물려지는것 + 자식은자식에맞는성질을추가하는것 + 부모로부터물려받은기능을변형시켜자신에맞는기능으로변형해서쓰는것 코드의안정성을고려해서자바는단일상속만을허용한다 단일상속으로인한제약사항의극복대안은인터페이스가있다 인터페이스는멀티플한상속을가능케한다. Syntax of a Java class: <modifier> class 자식클래스이름 extends 부모클래스이름 { }

6. Inheritance : 상속일경우생성자측면 상속이되면부모가가진모든성질 ( 멤버변수 / 메소드 ) 은자식에게물려지지만, 생성자는상속되지않는다 단자식생성자 Manager(){ // 이부분. } 첫라인에서부모디폴트생성자호출이일어난다 생성자는 2 가지종류로나뉠수있다 디폴트생성자 : 인자값없고, { } 안에서아무런일도하지않는생성자 명시적생성자 : 인자값이있고 { } 안에서객체변수초기화가일어난다

6. Inheritance : Polymorphism Polymorphism 이란하나의객체변수가여러가지모습과모양을갖는능력 Polymorphism is the ability to have many different forms; for example, the Manager class has access to methods from Employee class Employee employee = new Manager() //legal Emplyee employee1 = new Engineer() //legal Employee employee2 = new Seceratary() //lagal employee.department = "Sales"; // illegal Casting 필요!!

6. Inheritance : Heterogeneous Collections 같은데이터타입의값들로묶인집합 : Homogenous collections. MyDate[] dates = new MyDate[2]; dates[0] = new MyDate(22, 12, 1964); dates[1] = new MyDate(22, 7, 1964); 다른데이터 ( 클래스 ) 타입의값들로묶인집합 : Heterogeneous collections. Employee [] staff = new Employee[1024]; staff[0] = new Manager(); staff[1] = new Employee(); staff[2] = new Engineer();

6. Inheritance : The instanceof Operator public class Employee { public class Manager extends Employee { public class Engineer extends Employee { ---------------------------------------- public void dosomething(employee e) { if (e instanceof Manager) { // Process a Manager } else if (e instanceof Engineer) { // Process an Engineer } else { // Process any other type of Employee } }

6. Inheritance : Access Modifier private, default, protected, public 모두 4 개로클래스, 멤버변수, 메서드... 생성자에사용될수있다.

6. Inheritance : Overloading Method Names It can be used as follows: public void println(int i) public void println(float f) public void println(string s) 상속과관련없고하나의클래스에서발생되는원리 메소드의인자값은반드시달라야한다 ( 순서, 개수, 타입중하나라도 ) 메소드이름은반드시같아야한다 메소드의리턴타입은상관없다. 하는일은같으나처리하는데이터를달리할때쓰는기법이바로오버로딩

6. Inheritance : Overloading Constructors 메소드와마찬가지로생성자로오버로딩기법을쓴다 Example: public Employee(String name, double salary, Date DoB) public Employee(String name, double salary) public Employee(String name, Date DoB) 생성자의인자값은반드시달라야한다 ( 순서, 개수, 타입중하나라도 ) 생성자오버로딩에서는 this, super 키워드의사용법을반드시알아야함.!!

6. Inheritance : Overloading Constructors 1 public class Employee { 2 private static final double BASE_SALARY = 15000.00; 3 private String name; 4 private double salary; 5 private Date birthdate; 6 7 public Employee(String name, double salary, Date DoB) { 8 this.name = name; 9 this.salary = salary; 10 this.birthdate = DoB; 11 }

6. Inheritance : Overloading Constructors 12 public Employee(String name, double salary) { 13 this(name, salary, null); 14 } 15 public Employee(String name, Date DoB) { 16 this(name, BASE_SALARY, DoB); 17 } 18 public Employee(String name) { 19 this(name, BASE_SALARY); 20 } 21 }

6. Inheritance : Overriding Methods 상속관계에있는두클래스에서발생 자식이부모클래스의메소드를물려받아서 / 자신에맞는기능으로바꿔쓰는것 메소드선언부 ( 이름, 리턴타입, 인자값 ) 는반드시같아야한다 메소드의구현부는반드시달라야한다. 메소드의이름은같지는구현부가달라졌기에다른일을하는다른메소드이다

6. Inheritance : Overriding Methods public class Employee { } protected String name; protected double salary; protected Date birthdate; public String getdetails() { return Name: + name + \n + Salary: + salary; } public class Manager extends Employee { } protected String department; public String getdetails() { } return Name: + name + \n + Salary: + salary + "\n" + Manager of: + department;

6. Inheritance : Overriding Methods Virtual method invocation: Employee e = new Manager(); e.getdetails(); Compile-time type and runtime type

7. Advanced Class Features : static The static keyword 는변수, 메소드앞에붙여서쓸수있다. static 멤버는특정한어떤객체의구성원으로서가아니라클래스차원에서쓰이는멤버로간주된다 Thus static 멤버는클래스멤버혹은전역변수라칭해진다. static 이붙으면객체생성과관련이없다. 즉, 객체생성의과정없이도메모리에자동으로올라간다 ( 객체생성되기이전에 ) static 멤버에접근할때는객체생성과정을거치지않고접근가능하며 클래스이름. Static 멤버혹은바로 static 멤버를호출할수있다. static 한멤버는생성된객체들이다공유해서사용할수있다. static 블록안에서는 this 를사용할수없다

7. Advanced Class Features : static Count +counter : int = 0 -serialnumber : int c1 : Count c2 : Count serialnumber=1 serialnumber=2 1 public class Count { 2 private int serialnumber; 3 public static int counter = 0; 4 5 public Count() { 6 counter++; 7 serialnumber = counter; 8 } 9 } 클래스변수는생성된객체들이모두공유해서사용한다

7. Advanced Class Features : The Singleton Design Pattern ClientClass <<Uses>> Singleton -instance : Singleton +getinstance() : Singleton -Singleton() < Singleton 패턴으로작성하는방법 > 1. 자기자신의클래스에서클래스객체를생성 private static 으로 2. 생성된객체를리턴해오는 getinstance() 를 public 으로구현해놓음 3. 생성자는 private 으로막아놓음

7. Advanced Class Features : The Singleton Design Pattern <The Singleton code> 1 package shipping.domain; 2 3 public class Company { 4 private static Company instance = new Company(); 5 private String name; 6 private Vehicle[] fleet; 7 public static Company getcompany() { 8 return instance; 9 } 10 private Company() {...} 11 12 }

7. Advanced Class Features : The Singleton Design Pattern <Usage code> : 1 package shipping.reports; 2 3 import shipping.domain.*; 4 5 public class FuelNeedsReport { 6 public void generatetext(printstream output) { 7 Company c = Company.getCompany(); 8 // use Company object to retrieve the fleet vehicles 9 } 10 }

7. Advanced Class Features : final 내가마지막 ~~ 야 클래스앞의 final : 내가마지막클래스야 상속금지 메소드앞의 final : 내가마지막메소드야 오버라이딩금지 변수앞의 final : 냐가마지막변수야 상수임을의미 예 ) static final int MAX_SIZE = 100; final 키워드는주로 static 키워드와함께자주쓰인다

7. Advanced Class Features : interface <<interface>> Flyer +takeoff(); +land(); +fly(); Airplane Bird Superman +takeoff(){ } +land() { } +fly() { } +takeoff() { } +land() { } +fly() { } +buildnest() { } +layeggs() { } +takeoff() { } +land() { } +fly() { } +stopbullet() { }

7. Advanced Class Features : interface public interface Flyer { void takeoff(); public void land(); public void fly(); } public class Airplane implements Flyer { public void takeoff() { // accelerate until lift-off // raise landing gear } <<interface>> +takeoff() +land() +fly() Flyer Airplane +takeoff() +land() +fly()

7. Advanced Class Features : interface public class Bird extends Animal implements Flyer { public void takeoff() { } // take-off() 오버라이딩 public void land() { } // land( ) public void fly() { } // fly( ) public void buildnest() { / / buildnest() public void layeggs() { } // layeggs() public void eat() { } //Animal 클래스의메소드상속받음 받아서오버라이딩 }

7. Advanced Class Features : interface 인터페이스는클라이언트코드와해당인터페이스를구현해놓은클래스사의의규약이다 인터페이스는서로관련없는여러클래스들사이에서기능의공통점을추출하여 만든상위클래스이다. 특정인터페이스를상속받은클래스는그인터페이스가가지고있는모든추상메소드를모두구현해야하는책임이따른다. 단일상속과는달리인터페이스는멀티플한상속이가능하다 인터페이스의가장대표적인예는 JDBC 의 java.sql 패키지이다

7. Advanced Class Features : interface 인터페이스는클라이언트코드와해당인터페이스를구현해놓은클래스사의의규약이다 인터페이스는서로관련없는여러클래스들사이에서기능의공통점을추출하여 만든상위클래스이다. 특정인터페이스를상속받은클래스는그인터페이스가가지고있는모든추상메소드를모두구현해야하는책임이따른다. 단일상속과는달리인터페이스는멀티플한상속이가능하다 인터페이스의가장대표적인예는 JDBC 의 java.sql 패키지이다

7. Advanced Class Features : Abstract Classes Vehicle +calcfuelefficiency() : double +calctripdistance() : double Truck +calcfuelefficiency() : double +calctripdistance() : double RiverBarge +calcfuelefficiency() : double +calctripdistance() : double

7. Advanced Class Features : Abstract Classes 1 public abstract class Vehicle { 2 public abstract double calcfuelefficiency(); 3 public abstract double calctripdistance(); 4 } 1 public class Truck extends Vehicle { 2 public Truck(double max_load) {...} 3 4 public double calcfuelefficiency() { 5 /* calculate the fuel consumption of a truck at a given load */ 6 } 7 public double calctripdistrance() { 8 /* calculate the distance of this trip on highway */ 9 } 10 }

8. Exception : Exception Categories Throwable Error Exception StackOverflowError OutOfMemoryError RuntimeException ArithmeticException NullPointerException IndexOutOfBoundsException : 컴파일러가인식 X 컴파일은됨 IOException EOFException FileNotFoundException : 컴파일러가인식 O 컴파일안됨

8. Exception : Exception Example 1 public class HelloWorld { 2 public static void main (String args[]) { 3 int i = 0; 4 5 String greetings [ ] = { 6 "Hello world!, "No, I mean it!", "HELLO WORLD!! }; 7 8 while (i < 4) { 9 System.out.println (greetings[i]); 10 i++; 11 } 12 } 13 }

8. Exception : tryand catch Statements try { // 예외발생가능코드가들어온다 } catch (MyException myexception) { // 예외잡혔을때의코드가들어온다 } catch (Exception otherexcept) { // catch구문은여러번올수있다. 즉, 여러가지예외종류별로잡을수있다 } finally{ // 예외상관없이수행되어야하는코드블락 }

8. Exception :Exception Example Revisited public class HelloWorld2 { public static void main (String args[]) { int i = 0; String greetings [] = { "Hello world!", "No, I mean it!", 8 "HELLO WORLD!! }; while (i < 4) { try { System.out.println (greetings[i]); } catch (ArrayIndexOutOfBoundsException e){ System.out.println( i값을다시조정 "); i = -1; } finally { System.out.println( 이부분은항상수행됩니다 "); } i++; } } }

8. Exception : UserException class A{ int x = 10; int y = 0; public void go(){ if( y==0) throw new ZeroException(); // 이부분에서예외가발생!!! System.out.println( Uer Exception ); } } class Atest{ public static void main(string[ ]args){ A a = new A(); a.go(); } }

8. Exception : User Exception solution class A{ int x = 10; int y = 0; public void go() throws ZeroException { if( y==0) throw new ZeroException(); // 이부분에서예외가발생!!! System.out.println( Uer Exception ); } } class Atest{ public static void main(string[ ]args){ A a = new A(); try{ a.go(); // 예외가이곳으로날라오니여기서처리해줘야한다!! }catch(zeroexception e){ } } }

8. Exception : User Exception Creating class ZeroException extends Exception{ ZeroException(String message){ super(message); } ZeroException(){ this( This is UserException.. ); } }

9. Collection API : 핵심인터페이스

9. Collection API Collection Map Set HashSet List +add(index : int, element : Object) +get(index : int) : Object +remove(index : int) : Object +set(index : int, element Object) HashMap Properties ArrayList LinkedList Vector

9. Collection API : Vector 와 ArrayList - ArrayList는기존의 Vector를개선한것으로구현원리와기능적으로동일 - List인터페이스를구현하므로, 저장순서가유지되고중복을허용한다. - 데이터의저장공간으로배열을사용한다.( 배열기반 ) - Vector는자체적으로동기화처리가되어있으나 ArrayList는그렇지않다

9. Collection API : ArrayList vs. LinkedList - 순차적으로데이터를추가 / 삭제하는경우, ArrayList 가빠르다 - 비순차적으로데이터를추가 / 삭제하는경우, LinkedList 가빠르다. - 접근시간 (access time) 은 ArrayList 가빠르다.

9. Collection API : Set Example 1 import java.util.* 2 public class SetExample { 3 public static void main(string[] args) { 4 Set set = new HashSet(); 5 set.add("one"); 6 set.add("second"); 7 set.add("3rd"); 8 set.add(new Integer(4)); 9 set.add(new Float(5.0F)); 10 set.add("second"); // duplicate, not added 11 set.add(new Integer(4)); // duplicate, not added 12 System.out.println(set); 13 } 14 } [one, second, 5.0, 3rd, 4] 출력 : [one, second, 5.0, 3rd, 4] 중복을허용하지않는다.

9. Collection API : List Example 1 import java.util.* 2 public class ListExample { 3 public static void main(string[] args) { 4 List list = new ArrayList(); 5 list.add("one"); 6 list.add("second"); 7 list.add("3rd"); 8 list.add(new Integer(4)); 9 list.add(new Float(5.0F)); 10 list.add("second"); // duplicate, is added 11 list.add(new Integer(4)); // duplicate, is added 12 System.out.println(list); 13 } 14 } 출력 : [one, second, 3rd, 4, 5.0, second, 4] 순서가있다

9. Collection API : Maps Map 은자료를 key value 값을쌍으로저장하는특징을가지고있다 Map +put(key : Object, value : Object) : Object +get(key : Object) : Object +containskey(key : Object) : boolean +isempty() : boolean +size() : int +remove(key : Object) : Object HashMap Properties

9. Collection API : Properties 클래스 import java.util.properties; import java.util.enumeration; public class TestProperties { public static void main(string[] args) { Properties props = System.getProperties(); Enumeration prop_names = props.propertynames(); while ( prop_names.hasmoreelements() ) { String prop_name = (String) prop_names.nextelement(); String property = props.getproperty(prop_name); System.out.println("property " + prop_name + " is " + property + " "); } } }

9. Collection API : Properties 클래스 Properties 클래스는 OS 위에탑재되어있는시스템환경변수값들을불러올수있는클래스이다. Properties 클래스는 Map 의자식으로자료를 key value 를쌍으로저장하는특징이있다. 주요한메소드로는 PropertyNames(), getproperty() 등이있다 PropertyNames() 는리턴타입이 Enumeration 이다 Enumeration 객체에저장된자료를 sorting 하는패턴을익혀두자

9. Collection API : Iterator Iterator +hasnext() : boolean +next() : Object +remove() ListIterator +hasprevious() : boolean +previous() : Object +add(element : Object) +set(element : Object)

9. Collection API : Enumeration, Iterator, ListIterator - 컬렉션클래스에저장된데이터를접근하는데사용되는인터페이스이다 - Enumeration 는 Iterator 의구버젼이다. - Iterator 의접근성을향상시킨것이 ListIterator 이다.( 단방향 양방향 )

10. AWT:AWT(Abstract Window Toolkit) 란? AWT - GUI프로그래밍 ( 윈도우프로그래밍 ) 을위한도구 - GUI프로그래밍에필요한다양한컴포넌트를제공한다. - Java로구현하지않고, OS의컴포넌트를그대로사용한다. Swing - AWT를확장한 GUI프로그래밍도구 - AWT보다더많은종류의컴포넌트를제공한다. - OS의컴포넌트를사용하지않고, 순수한 Java로구현하였다.

10. AWT : - 모든 AWT 컴포넌트의최고조상은 java.awt.component 클래스이다.

10. AWT : 컨테이너 (Container) 1. 독립적인컨테이너 독립적으로사용될수있으며, 다른컴포넌트나종속적인컨테이너를포함할수있다. 2. 종속적인컨테이너 독립적으로사용될수없으며, 다른컨테이너에포함되어야함

10. AWT : 주요컴포넌트.. Frame

10. AWT : 주요컴포넌트.. Button

10. AWT : 주요컴포넌트.. Choice - 여러 item 중에서하나를선택할수있게해주는컴포넌트

10. AWT : 주요컴포넌트.. Label - 화면에텍스트를표시하는데사용되는컴포넌트

10. AWT : 주요컴포넌트.. TextFiel

10. AWT : 주요컴포넌트.. TextArea

10. AWT : Layout Manager - 레이아웃매니저는컨테이너에포함된컴포넌트의배치를자동관리한다 -AWT 에서는아래와같이 5 개의레이아웃매니저를제공한다. BorderLayout, FlowLayout, GridLayout, CardLayout, GridbagLayout

10. Swing Hierachy

10. Swing private static void createandshowgui(){ //Create and set up the window. JFrame frame = new JFrame("Hi.."); frame.setdefaultcloseoperation(jframe.exit_on_close); //Add a label. JLabel label = new JLabel("Hello World"); frame.getcontentpane().add(label); //Display the window. frame.pack(); frame.setvisible(true); }

11. Event Handling

11. Event Handling

11. Event Handling Category Interface Name Methods Action ActionListener actionperformed(actionevent) Item ItemListener itemstatechanged(itemevent) Mouse MouseListener mousepressed(mouseevent) mousereleased(mouseevent) mouseentered(mouseevent) mouseexited(mouseevent) mouseclicked(mouseevent) MouseMotion MouseMotionListener mousedragged(mouseevent) mousemoved(mouseevent)

12. Thread : Process Thread 프로그램 : 실행가능한파일 (HDD) 프로세스 : 실행중인프로그램 ( 메모리 )

12. Thread : Process Thread 프로세스 : 실행중인프로그램, 자원 (resources) 과쓰레드로구성 쓰레드 : 프로세스내에서진행되는세부적인작업단위 모든프로세스는하나이상의쓰레드를가지고있다. 프로세스 : 쓰레드 = 공장 : 일꾼 싱글쓰레드프로세스 = 자원 + 쓰레드 프로세스 ( 공장 ) 멀티쓰레드프로세스 = 자원 + 쓰레드 + 쓰레드 + + 쓰레드 쓰레드 ( 일꾼 )

12. Thread : Process Thread 하나의새로운프로세스를생성하는것보다 하나의새로운쓰레드를생성하는것이더적은비용이든다. - 2 프로세스 1 쓰레드 vs. 1 프로세스 2 쓰레드 vs.

12. Thread : 단일쓰레드 다중쓰레드 main() main() 작업 1() 작업 1 수행 작업 1 수행 작업 3 수행 작업 2 수행 작업 2() 작업 2 수행 작업 3() 작업 3 수행 단일쓰레드 다중쓰레드

12. Thread : 단일쓰레드 다중쓰레드 단일쓰레드 : 하나의작업을수행한후, 다음작업을수행 쓰레드의 Process 화 즉, 한개의프로세스를사용하는것과같음 다중쓰레드 : 여러작업이거의동시에수행 프로그램의수행속도가행상되므로단일쓰레드보다성능이좋다 c.f main() : 다른쓰레드를서비스해주는쓰레드를데몬쓰레드라고한다. 우리가지금까지작성해온자바프로그램은모두단일쓰레드방식. 즉, jvm 이작동하면서 main() 가수행돠는데이 main() 자체가하나의 쓰레드 데몬쓰레드다. 다른모든메소드의호출은결국 main() 의서비스에의해서호출되는것이다.

12. Thread : 멀티쓰레드의장단점 많은프로그램들이멀티쓰레드로작성되어있다. 그러나, 멀티쓰레드프로그래밍이장점만있는것은아니다. 장점 - 자원을보다효율적으로사용할수있다. - 사용자에대한응답성 (responseness) 이향상된다. - 작업이분리되어코드가간결해진다. 여러모로좋다. 단점 - 동기화 (synchronization) 에주의해야한다. - 교착상태 (dead-lock) 가발생하지않도록주의해야한다. - 각쓰레드가효율적으로고르게실행될수있게해야한다. 프로그래밍할때고려해야할사항들이많다.

12. Thread : 쓰레드의구현과실행

12. Thread : 쓰레드의상태 (state of thread)

12. Thread : 쓰레드의상태 (state of thread) New Thread Blocking Destroy Thread start() sleep () Runnable yield() run () Running

12. Thread : sleep() public class Runner implements Runnable { public void run() { while (true) { try { Thread.sleep(10); } catch (InterruptedException e) { } } } }

12. Thread : Basic Control of Threads Testing threads: isalive() Thread priority: getpriority() setpriority() Putting threads on hold: Thread.sleep() join() Thread.yield()

12. Thread : synchronized Keyword public class MyStack { int idx = 0; char [] data = new char[6]; public void push(char c) { data[idx] = c; idx++; } public char pop() { idx--; return data[idx]; } }

12. Thread : The Object Lock Flag public void push(char c) { synchronized (this) { data[idx] = c; idx++; } } public char pop() { synchronized (this) { idx--; return data[idx]; } }

12. Thread : The Object Lock Flag public void push(char c) { synchronized(this) { : : } } public synchronized void push(char c) { : : }

12. Thread : wait(), notify(), notifyall() - 동기화의효율을높이기위해 wait(), notify() 를사용. - Object 클래스에정의되어있으며, 동기화블록내에서만사용할수있다. wait() 객체의 lock 을풀고해당객체의쓰레드를 waiting pool 에넣는다 notify() waiting pool 에서대기중인쓰레드중의하나를깨운다. notifyall() waiting pool 에서대기중인모든쓰레드를깨운다.

13. I/O : 스트림 (Stream) Stream : - 데이터를소스에서전달하거나목적지로수신하는길, 데이터의흐름 - 스트림은단방향이다. - FIFO 구조이다. Stream Source read program write Destination Input Stream Output Stream

13. I/O : 입력, 출력스트림 입력 출력 Byte Stream InputStream OutputStream Character Stream Reader Writer InputStream의메서드 : int read(), int read(byte[ ] b) OutputStream의메서드 : void write( ), void write(byte[ ] b) Reader의메서드 : int read( ), int read( char[ ] ch) Writer의메서드 : void write( ), void write( char [ ] ch)

13. I/O : 키보드입력읽기 System.in 을통해 Stream 으로들어옴 InputStream 입력을문자스트림으로읽어들임 한줄전체를읽어들임 < 소스코드의패턴 > InputStreamReader BufferedReader 1. 스트림생성 : InputStreamReader is = new InputStreamReader(System.in); BufferedReader br = new BufferdReader(is); 2. 읽어들임 : String line = br.readline(); 3. 계속읽어들여서콘솔창으로출력 : while(line!= null){ System.out.println(line); line = br.readline(); }

13. I/O : Scanner Java 5.0 부터 java.util.scanner 제공 BufferedReader 와 FileReader, StringTokenizer 의조합대신사용 키보드입력사용 Scanner skb = new Scanner(System.in) System.out.print("Enter name: "); String name = skb.nextline(); System.out.print("Enter age: "); int age = skb.nextint(); File 에서사용 Scanner sf = new Scanner( inputfile.txt )

13. I/O import java.io.*; import java.util.*; public class ScannerTest { public static void main(string[] args) { Scanner sf = new Scanner("c:\\temp\\phone.txt"); String name; int number1; // 전화번호첫번째자리 int number2; // 전화번호두번째자리 int number3; // 전화번호세번째자리 while (sf.hasnextline()) { name = sf.next(); number1 = sf.nextint(); number2 = sf.nextint(); number3 = sf.nextint(); System.out.println(name + number1 + number2 + number3); }

14. Networking : TCP 와 UDP 소켓프로그래밍이란? - 소켓을이용한통신프로그래밍을뜻한다. - 소켓 (socket) 이란, 프로세스간의통신에사용되는양쪽끝단 (end point) - 전화할때양쪽에전화기가필요한것처럼, 프로세스간의통신에서도양쪽에소켓이필요하다.

14. Networking : TCP 소켓프로그래밍 1. 서버는서버소켓을사용해서서버의특정포트에서클라이언트의연결요청을처리할준비를한다. 2. 클라이언트는접속할서버의 IP 주소와포트정보로소켓을생성해서서버에연결을요청한다. 3. 서버소켓은클라이언트의연결요청을받으면서버에새로운소켓을생성해서클라이언트의소켓과연결되도록한다. 4. 이제클라이언트의소켓과새로생성된서버의소켓은서버소켓과관계없이 1:1 통신을한다.

14. Networking : TCP 소켓프로그래밍 <Server 측코드 > 1. 서버소켓을생성 : ServerSocket server = new ServerSocket(port); 2. 클라이언트가접속하면소켓을리턴 : Socket s = server.accept(); 3. 소켓으로부터스트림생성 :InputStream in= s.getinputstream(); <Client 측코드 > 1. 소켓을생성 : Socket s = new Socket(ip, port); 2. 소켓으로부터스트림생성 : OutputStream os = s.getoutputstream(); 3. 서버측으로데이터를전송함 : os.println(data);