RMI(Remote Method Invocation)

Size: px
Start display at page:

Download "RMI(Remote Method Invocation)"

Transcription

1 Java SE Programming

2 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

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

4 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이개발 언어에객체지향특성확장

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

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

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

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

9 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! ); }

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

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

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

13 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--;} // 채널낮추기 }

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

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

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

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

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

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

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

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

22 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

23 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

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

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

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

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

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

29 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, 0x ~0xffffffff)

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

31 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 : int x = 59; int z = x; long 8byte long big = ; 실수형 float 4byte -3.4E38 ~ 3.4E38 float f = 32.5f double 8byte -1.7E308 ~ 1.7E308 double d = 23.34

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

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

34 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

35 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 = F; // F is float, OK float z1 = ; // is double, illegal

36 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; }

37 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."); }

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

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

40 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!");

41 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");

42 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");

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

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

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

46 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 는메모리상저장되는구조다름

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

48 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);

49 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

50 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

51 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 = ""; }

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

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

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

55 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 필요!!

56 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();

57 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 } }

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

59 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) 상속과관련없고하나의클래스에서발생되는원리 메소드의인자값은반드시달라야한다 ( 순서, 개수, 타입중하나라도 ) 메소드이름은반드시같아야한다 메소드의리턴타입은상관없다. 하는일은같으나처리하는데이터를달리할때쓰는기법이바로오버로딩

60 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 키워드의사용법을반드시알아야함.!!

61 6. Inheritance : Overloading Constructors 1 public class Employee { 2 private static final double BASE_SALARY = ; 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 }

62 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 }

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

64 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;

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

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

67 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 } 클래스변수는생성된객체들이모두공유해서사용한다

68 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 으로막아놓음

69 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() {...} }

70 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 }

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

72 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() { }

73 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()

74 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 클래스의메소드상속받음 받아서오버라이딩 }

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

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

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

78 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 }

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

80 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 }

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

82 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++; } } }

83 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(); } }

84 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){ } } }

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

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

87 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

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

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

90 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] 중복을허용하지않는다.

91 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] 순서가있다

92 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

93 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 + " "); } } }

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

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

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

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

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

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

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

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

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

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

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

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

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

107 10. Swing Hierachy

108 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); }

109 11. Event Handling

110 11. Event Handling

111 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)

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

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

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

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

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

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

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

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

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

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

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

123 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]; } }

124 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]; } }

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

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

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

128 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)

129 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(); }

130 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 )

131 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); }

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

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

134 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);

PowerPoint Presentation

PowerPoint Presentation Class - Property Jo, Heeseung 목차 section 1 클래스의일반구조 section 2 클래스선언 section 3 객체의생성 section 4 멤버변수 4-1 객체변수 4-2 클래스변수 4-3 종단 (final) 변수 4-4 멤버변수접근방법 section 5 멤버변수접근한정자 5-1 public 5-2 private 5-3 한정자없음

More information

1

1 1 1....6 1.1...6 2. Java Architecture...7 2.1 2SDK(Software Development Kit)...8 2.2 JRE(Java Runtime Environment)...9 2.3 (Java Virtual Machine, JVM)...10 2.4 JVM...11 2.5 (runtime)jvm...12 2.5.1 2.5.2

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 @ Lesson 2... ( ). ( ). @ vs. logic data method variable behavior attribute method field Flow (Type), ( ) member @ () : C program Method A ( ) Method B ( ) Method C () program : Java, C++, C# data @ Program

More information

PowerPoint Presentation

PowerPoint Presentation public class SumTest { public static void main(string a1[]) { int a, b, sum; a = Integer.parseInt(a1[0]); b = Integer.parseInt(a1[1]); sum = a + b ; // 두수를더하는부분입니다 System.out.println(" 두수의합은 " + sum +

More information

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

q 이장에서다룰내용 1 객체지향프로그래밍의이해 2 객체지향언어 : 자바 2 객체지향프로그래밍 IT CookBook, 자바로배우는쉬운자료구조 q 이장에서다룰내용 1 객체지향프로그래밍의이해 2 객체지향언어 : 자바 2 q 객체지향프로그래밍의이해 v 프로그래밍기법의발달 A 군의사업발전 1 단계 구조적프로그래밍방식 3 q 객체지향프로그래밍의이해 A 군의사업발전 2 단계 객체지향프로그래밍방식 4 q 객체지향프로그래밍의이해 v 객체란무엇인가

More information

02 C h a p t e r Java

02 C h a p t e r Java 02 C h a p t e r Java Bioinformatics in J a va,, 2 1,,,, C++, Python, (Java),,, (http://wwwbiojavaorg),, 13, 3D GUI,,, (Java programming language) (Sun Microsystems) 1995 1990 (green project) TV 22 CHAPTER

More information

Microsoft PowerPoint - 04-UDP Programming.ppt

Microsoft PowerPoint - 04-UDP Programming.ppt Chapter 4. UDP Dongwon Jeong djeong@kunsan.ac.kr http://ist.kunsan.ac.kr/ Dept. of Informatics & Statistics 목차 UDP 1 1 UDP 개념 자바 UDP 프로그램작성 클라이언트와서버모두 DatagramSocket 클래스로생성 상호간통신은 DatagramPacket 클래스를이용하여

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 클래스, 객체, 메소드 ( 실습 ) 손시운 ssw5176@kangwon.ac.kr 예제 1. 필드만있는클래스 텔레비젼 2 예제 1. 필드만있는클래스 3 예제 2. 여러개의객체생성하기 4 5 예제 3. 메소드가추가된클래스 public class Television { int channel; // 채널번호 int volume; // 볼륨 boolean

More information

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

07 자바의 다양한 클래스.key [ 07 ] . java.lang Object, Math, String, StringBuffer Byte, Short, Integer, Long, Float, Double, Boolean, Character. java.util Random, StringTokenizer Calendar, GregorianCalendar, Date. Collection, List,

More information

JAVA PROGRAMMING 실습 08.다형성

JAVA PROGRAMMING 실습 08.다형성 2015 학년도 2 학기 1. 추상메소드 선언은되어있으나코드구현되어있지않은메소드 abstract 키워드사용 메소드타입, 이름, 매개변수리스트만선언 public abstract String getname(); public abstract void setname(string s); 2. 추상클래스 abstract 키워드로선언한클래스 종류 추상메소드를포함하는클래스

More information

제11장 프로세스와 쓰레드

제11장 프로세스와 쓰레드 제9장자바쓰레드 9.1 Thread 기초 (1/5) 프로그램 명령어들의연속 (a sequence of instruction) 프로세스 / Thread 실행중인프로그램 (program in execution) 프로세스생성과실행을위한함수들 자바 Thread 2 9.1 Thread 기초 (2/5) 프로세스단위작업의문제점 프로세스생성시오버헤드 컨텍스트스위치오버헤드

More information

PowerPoint Presentation

PowerPoint Presentation Package Class 1 Heeseung Jo 목차 section 1 패키지개요와패키지의사용 section 2 java.lang 패키지의개요 section 3 Object 클래스 section 4 포장 (Wrapper) 클래스 section 5 문자열의개요 section 6 String 클래스 section 7 StringBuffer 클래스 section

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 @ Lesson 1,..... @ 1 Green Project 1991 Oak Java 1995. 5 December '90 by Patrick Naughton, Mike Sheridan and James Gosling Embedded in various consumer electronic device 1992. 9. 3 Star 7 1993 www portability

More information

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

gnu-lee-oop-kor-lec06-3-chap7 어서와 Java 는처음이지! 제 7 장상속 Super 키워드 상속과생성자 상속과다형성 서브클래스의객체가생성될때, 서브클래스의생성자만호출될까? 아니면수퍼클래스의생성자도호출되는가? class Base{ public Base(String msg) { System.out.println("Base() 생성자 "); ; class Derived extends Base

More information

슬라이드 1

슬라이드 1 UNIT 16 예외처리 로봇 SW 교육원 3 기 최상훈 학습목표 2 예외처리구문 try-catch-finally 문을사용핛수있다. 프로그램오류 3 프로그램오류의종류 컴파일에러 (compile-time error) : 컴파일실행시발생 럮타임에러 (runtime error) : 프로그램실행시발생 에러 (error) 프로그램코드에의해서해결될수없는심각핚오류 ex)

More information

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

Microsoft PowerPoint 자바-기본문법(Ch2).pptx 자바기본문법 1. 기본사항 2. 자료형 3. 변수와상수 4. 연산자 1 주석 (Comments) 이해를돕기위한설명문 종류 // /* */ /** */ 활용예 javadoc HelloApplication.java 2 주석 (Comments) /* File name: HelloApplication.java Created by: Jung Created on: March

More information

JAVA PROGRAMMING 실습 09. 예외처리

JAVA PROGRAMMING 실습 09. 예외처리 2015 학년도 2 학기 예외? 프로그램실행중에발생하는예기치않은사건 예외가발생하는경우 정수를 0으로나누는경우 배열의크기보다큰인덱스로배열의원소를접근하는경우 파일의마지막부분에서데이터를읽으려고하는경우 예외처리 프로그램에문제를발생시키지않고프로그램을실행할수있게적절한조치를취하는것 자바는예외처리기를이용하여예외처리를할수있는기법제공 자바는예외를객체로취급!! 나뉨수를입력하시오

More information

Microsoft PowerPoint - CSharp-10-예외처리

Microsoft PowerPoint - CSharp-10-예외처리 10 장. 예외처리 예외처리개념 예외처리구문 사용자정의예외클래스와예외전파 순천향대학교컴퓨터학부이상정 1 예외처리개념 순천향대학교컴퓨터학부이상정 2 예외처리 오류 컴파일타임오류 (Compile-Time Error) 구문오류이기때문에컴파일러의구문오류메시지에의해쉽게교정 런타임오류 (Run-Time Error) 디버깅의절차를거치지않으면잡기어려운심각한오류 시스템에심각한문제를줄수도있다.

More information

예제 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

예제 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 제 10 장상속 예제 1) ConstructorTest.java class Parent public Parent() super - default"); public Parent(int i) this("hello"); super(int) constructor" + i); public Parent(char c) this(); super(char) constructor

More information

<4D F736F F F696E74202D20C1A63038C0E520C5ACB7A1BDBABFCD20B0B4C3BC4928B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

<4D F736F F F696E74202D20C1A63038C0E520C5ACB7A1BDBABFCD20B0B4C3BC4928B0ADC0C729205BC8A3C8AF20B8F0B5E55D> Power Java 제 8 장클래스와객체 I 이번장에서학습할내용 클래스와객체 객체의일생직접 메소드클래스를 필드작성해 UML 봅시다. QUIZ 1. 객체는 속성과 동작을가지고있다. 2. 자동차가객체라면클래스는 설계도이다. 먼저앞장에서학습한클래스와객체의개념을복습해봅시다. 클래스의구성 클래스 (class) 는객체의설계도라할수있다. 클래스는필드와메소드로이루어진다.

More information

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

Microsoft PowerPoint - Supplement-03-TCP Programming.ppt [호환 모드] - Socket Programming in Java - 목차 소켓소개 자바에서의 TCP 프로그램작성방법 주요클래스와메소드 HTTP 프로토콜을이용한예제 에코프로그램 Q/A 에코프로그램 - EchoServer 에코프로그램 - EchoClient TCP Programming 1 소켓소개 IP, Port, and Socket 포트 (Port): 전송계층에서통신을수행하는응용프로그램을찾기위한주소

More information

Design Issues

Design Issues 11 COMPUTER PROGRAMMING INHERIATANCE CONTENTS OVERVIEW OF INHERITANCE INHERITANCE OF MEMBER VARIABLE RESERVED WORD SUPER METHOD INHERITANCE and OVERRIDING INHERITANCE and CONSTRUCTOR 2 Overview of Inheritance

More information

12-file.key

12-file.key 11 (String).. java.lang.stringbuffer. s String s = "abcd"; s = s + "e"; a b c d e a b c d e ,., "910359,, " "910359" " " " " (token) (token),, (delimiter). java.util.stringtokenizer String s = "910359,,

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 @ Lesson 3 if, if else, if else if, switch case for, while, do while break, continue : System.in, args, JOptionPane for (,, ) @ vs. logic data method variable Data Data Flow (Type), ( ) @ Member field

More information

01-OOPConcepts(2).PDF

01-OOPConcepts(2).PDF Object-Oriented Programming Concepts Tel: 02-824-5768 E-mail: hhcho@selabsoongsilackr? OOP (Object) (Encapsulation) (Message) (Class) (Inheritance) (Polymorphism) (Abstract Class) (Interface) 2 1 + = (Dependency)

More information

Microsoft PowerPoint - 2강

Microsoft PowerPoint - 2강 컴퓨터과학과 김희천교수 학습개요 Java 언어문법의기본사항, 자료형, 변수와상수선언및사용법, 각종연산자사용법, if/switch 등과같은제어문사용법등에대해설명한다. 또한 C++ 언어와선언 / 사용방법이다른 Java의배열선언및사용법에대해서설명한다. Java 언어의효과적인활용을위해서는기본문법을이해하는것이중요하다. 객체지향의기본개념에대해알아보고 Java에서어떻게객체지향적요소를적용하고있는지살펴본다.

More information

rmi_박준용_final.PDF

rmi_박준용_final.PDF (RMI) - JSTORM http://wwwjstormpekr (RMI)- Document title: Document file name: Revision number: Issued by: Document Information (RMI)- rmi finaldoc Issue Date: Status:

More information

JVM 메모리구조

JVM 메모리구조 조명이정도면괜찮조! 주제 JVM 메모리구조 설미라자료조사, 자료작성, PPT 작성, 보고서작성. 발표. 조장. 최지성자료조사, 자료작성, PPT 작성, 보고서작성. 발표. 조원 이용열자료조사, 자료작성, PPT 작성, 보고서작성. 이윤경 자료조사, 자료작성, PPT작성, 보고서작성. 이수은 자료조사, 자료작성, PPT작성, 보고서작성. 발표일 2013. 05.

More information

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µå

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µå 기초통계프로그래밍 클래스, 객체, 변수, 메소드 hmkang@hallym.ac.kr 금융정보통계학과 강희모 ( 금융정보통계학과 ) 기초통계프로그래밍 1 / 26 자바구성파일 소스파일 소스파일 : 사용자가직접에디터에입력하는파일로자바프로그램언어가제공하는형식으로제작 소스파일의확장자는.java 임 컴파일 : javac 명령어를이용하여프로그래머가만든소스파일을컴파일하여실행파일.class

More information

Microsoft PowerPoint - 03-TCP Programming.ppt

Microsoft PowerPoint - 03-TCP Programming.ppt Chapter 3. - Socket in Java - 목차 소켓소개 자바에서의 프로그램작성방법 주요클래스와메소드 HTTP 프로토콜을이용한예제 에코프로그램 에코프로그램 - EchoServer 에코프로그램 - EchoClient Q/A 1 1 소켓소개 IP,, and Socket 포트 (): 전송계층에서통신을수행하는응용프로그램을찾기위한주소 소켓 (Socket):

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 Lab 4 ADT Design 클래스로정의됨. 모든객체들은힙영역에할당됨. 캡슐화 (Encapsulation) : Data representation + Operation 정보은닉 (Information Hiding) : Opertion부분은가려져있고, 사용자가 operation으로만사용가능해야함. 클래스정의의형태 public class Person { private

More information

JAVA PROGRAMMING 실습 05. 객체의 활용

JAVA PROGRAMMING 실습 05. 객체의 활용 public class Person{ public String name; public int age; } public Person(){ } public Person(String s, int a){ name = s; age = a; } public String getname(){ return name; } @ 객체의선언 public static void main(string

More information

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

(Microsoft PowerPoint - java1-lecture11.ppt [\310\243\310\257 \270\360\265\345]) 예외와예외클래스 예외처리 514760-1 2016 년가을학기 12/08/2016 박경신 오류의종류 에러 (Error) 하드웨어의잘못된동작또는고장으로인한오류 에러가발생되면 JVM실행에문제가있으므로프로그램종료 정상실행상태로돌아갈수없음 예외 (Exception) 사용자의잘못된조작또는개발자의잘못된코딩으로인한오류 예외가발생되면프로그램종료 예외처리 추가하면정상실행상태로돌아갈수있음

More information

C# Programming Guide - Types

C# Programming Guide - Types C# Programming Guide - Types 최도경 lifeisforu@wemade.com 이문서는 MSDN 의 Types 를요약하고보충한것입니다. http://msdn.microsoft.com/enus/library/ms173104(v=vs.100).aspx Types, Variables, and Values C# 은 type 에민감한언어이다. 모든

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 실습 1 배효철 th1g@nate.com 1 목차 조건문 반복문 System.out 구구단 모양만들기 Up & Down 2 조건문 조건문의종류 If, switch If 문 조건식결과따라중괄호 { 블록을실행할지여부결정할때사용 조건식 true 또는 false값을산출할수있는연산식 boolean 변수 조건식이 true이면블록실행하고 false 이면블록실행하지않음 3

More information

Cluster management software

Cluster management software 자바네트워크프로그래밍 (OCJP 국제공인자격취득중심 ) 충북대학교 최민 기본예제 예외클래스를정의하고사용하는예제 class NewException extends Exception { public class ExceptionTest { static void methoda() throws NewException { System.out.println("NewException

More information

슬라이드 1

슬라이드 1 UNIT 12 상속과오버라이딩 로봇 SW 교육원 2 기 최상훈 학습목표 2 클래스를상속핛수있다. 메소드오버라이딩을사용핛수있다. 패키지선언과 import 문을사용핛수있다. 상속 (inheritance) 3 상속이란 기존의클래스를기반으로새로운클래스를작성 두클래스를부모와자식으로관계를맺어주는것 자식은부모의모든멤버를상속받음 연관된일렦의클래스에대핚공통적인규약을정의 class

More information

오버라이딩 (Overriding)

오버라이딩 (Overriding) WindowEvent WindowEvent 윈도우가열리거나 (opened) 닫힐때 (closed) 활성화되거나 (activated) 비활성화될때 (deactivated) 최소화되거나 (iconified) 복귀될때 (deiconified) 윈도우닫힘버튼을누를때 (closing) WindowEvent 수신자 abstract class WindowListener

More information

PowerPoint Presentation

PowerPoint Presentation public class SumTest { public static void main(string a1[]) { int a, b, sum; a = Integer.parseInt(a1[0]); b = Integer.parseInt(a1[1]); sum = a + b ; // 두수를더하는부분입니다 System.out.println(" 두수의합은 " + sum +

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 인터페이스 배효철 th1g@nate.com 1 목차 인터페이스의역할 인터페이스선언 인터페이스구현 인터페이스사용 타입변환과다형성 인터페이스상속 디폴트메소드와인터페이스확장 2 인터페이스의역할 인터페이스란? 개발코드와객체가서로통신하는접점 개발코드는인터페이스의메소드만알고있으면 OK 인터페이스의역할 개발코드가객체에종속되지않게 -> 객체교체할수있도록하는역할 개발코드변경없이리턴값또는실행내용이다양해질수있음

More information

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

iii. Design Tab 을 Click 하여 WindowBuilder 가자동으로생성한 GUI 프로그래밍환경을확인한다. Eclipse 개발환경에서 WindowBuilder 를이용한 Java 프로그램개발 이예는 Java 프로그램의기초를이해하고있는사람을대상으로 Embedded Microcomputer 를이용한제어시스템을 PC 에서 Serial 통신으로제어 (Graphical User Interface (GUI) 환경에서 ) 하는프로그램개발예를설명한다. WindowBuilder:

More information

No Slide Title

No Slide Title 상속 이충기 명지대학교컴퓨터공학과 상속 Q: 건설회사는기존아파트와조금다르거나추가적인특징들을가진새아파트를지을때어떻게하는가? A: 2 상속 상속 (inheritance) 은클래스들을연관시키는자연스럽고계층적인방법이다. 상속은객체지향프로그래밍의가장중요한개념중의하나이다. 상속은 은 이다 라는관계 (is-a relationship) 를나타낸다. 이관계를적용하여클래스들을상하관계로연결하는것이상속이다.

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 오류처리 손시운 ssw5176@kangwon.ac.kr 오류메시지를분석한다. 오류메시지에서많은내용을알수있다. 2 디버깅 디버거를사용하면프로그램에서쉽게오류를감지하고진단할수있다. 디버거는중단점을설정하여서프로그램의실행을제어할수있으며문장 단위로실행하거나변수의값을살펴볼수있다. 3 이클립스에서디버깅 4 이클립스에서디버깅 5 이클립스의디버깅명령어 6 예외처리

More information

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

JAVA 프로그래밍실습 실습 1) 실습목표 - 메소드개념이해하기 - 매개변수이해하기 - 새메소드만들기 - Math 클래스의기존메소드이용하기 (   ) 문제 - 직사각형모양의땅이있다. 이땅의둘레, 면적과대각 JAVA 프로그래밍실습 실습 1) 실습목표 - 메소드개념이해하기 - 매개변수이해하기 - 새메소드만들기 - Math 클래스의기존메소드이용하기 ( http://java.sun.com/javase/6/docs/api ) 문제 - 직사각형모양의땅이있다. 이땅의둘레, 면적과대각선의길이를계산하는메소드들을작성하라. 직사각형의가로와세로의길이는주어진다. 대각선의길이는 Math클래스의적절한메소드를이용하여구하라.

More information

PowerPoint Presentation

PowerPoint Presentation Package Class 3 Heeseung Jo 목차 section 1 패키지개요와패키지의사용 section 2 java.lang 패키지의개요 section 3 Object 클래스 section 4 포장 (Wrapper) 클래스 section 5 문자열의개요 section 6 String 클래스 section 7 StringBuffer 클래스 section

More information

JUNIT 실습및발표

JUNIT 실습및발표 JUNIT 실습및발표 JUNIT 접속 www.junit.org DownLoad JUnit JavaDoc API Document 를참조 JUNIT 4.8.1 다운로드 설치파일 (jar 파일 ) 을다운로드 CLASSPATH 를설정 환경변수에서설정 실행할클래스에서 import JUnit 설치하기 테스트실행주석 @Test Test 를실행할 method 앞에붙임 expected

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 Lecture 02 프로그램구조및문법 Kwang-Man Ko kkmam@sangji.ac.kr, compiler.sangji.ac.kr Department of Computer Engineering Sang Ji University 2018 자바프로그램기본구조 Hello 프로그램구조 sec01/hello.java 2/40 자바프로그램기본구조 Hello 프로그램구조

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 클래스, 객체, 메소드 손시운 ssw5176@kangwon.ac.kr 실제세계는객체로이루어진다. 2 객체와메시지 3 객체지향이란? 실제세계를모델링하여소프트웨어를개발하는방법 4 객체 5 객체란? 객체 (Object) 는상태와동작을가지고있다. 객체의상태 (state) 는객체의특징값 ( 속성 ) 이다. 객체의동작 (behavior) 또는행동은객체가취할수있는동작

More information

Microsoft PowerPoint - Lect04.pptx

Microsoft PowerPoint - Lect04.pptx OBJECT ORIENTED PROGRAMMING Object Oriented Programming 이강의록은 Power Java 저자의강의록을사용했거나재편집된것입니다. Class 와 object Class 와객체 클래스의일생 메소드 필드 String Object Class 와객체 3 클래스 클래스의구성 클래스 (l (class): 객체를만드는설계도 클래스로부터만들어지는각각의객체를특별히그클래스의인스턴스

More information

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍 Power Java 제 20 장패키지 이번장에서학습할내용 패키지의개념 패키지로묶는방법 패키지사용 기본패키지 유틸리티패키지 패키지는연관된클래스들을묶는기법입니다. 패키지란? 패키지 (package) : 클래스들을묶은것 자바라이브러리도패키지로구성 ( 예 ) java.net 패키지 네트워크관련라이브러리 그림 20-1. 패키지의개념 예제 패키지생성하기 Q: 만약패키지문을사용하지않은경우에는어떻게되는가?

More information

PowerPoint Presentation

PowerPoint Presentation public class SumTest { public static void main(string a1[]) { int a, b, sum; a = Integer.parseInt(a1[0]); b = Integer.parseInt(a1[1]); sum = a + b ; // 두수를더하는부분입니다 System.out.println(" 두수의합은 " + sum +

More information

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍 Power Java 제 7 장클래스와객체 이번장에서학습할내용 객체지향이란? 객체 메시지 클래스 객체지향의장점 String 클래스 객체지향개념을완벽하게이해해야만객체지향설계의이점을활용할수있다. 실제세계는객체로이루어진다. 객체지향이란? 실제세계를모델링하여소프트웨어를개발하는방법 절차지향과객체지향 절차지향프로그래밍 (procedural programming): 문제를해결하는절차를중요하게생각하는방법

More information

Network Programming

Network Programming Part 5 확장된 Network Programming 기술 1. Remote Procedure Call 2. Remote Method Invocation 3. Object Request Broker 2. Java RMI

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 인터페이스, 람다식, 패키지 ( 실습 ) 손시운 ssw5176@kangwon.ac.kr 예제 1. 홈네트워킹 public interface RemoteControl { public void turnon(); // 가전제품을켠다. public void turnoff(); // 가전제품을끈다. 인터페이스를구현 public class Television

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 예외처리 배효철 th1g@nate.com 1 목차 예외와예외클래스 실행예외 예외처리코드 예외종류에따른처리코드 자동리소스닫기 예외처리떠넘기기 사용자정의예외와예외발생 예외와예외클래스 구문오류 예외와예외클래스 구문오류가없는데실행시오류가발생하는경우 예외와예외클래스 import java.util.scanner; public class ExceptionExample1

More information

Semantic Consistency in Information Exchange

Semantic Consistency in Information Exchange 제 6 장제어 (Control) 6.1 구조적프로그래밍 (Structured Programming) 6.2 예외 (Exceptions) Reading Chap. 7 숙대창병모 1 6.1 구조적프로그래밍 숙대창병모 2 Fortran 제어구조 10 IF (X.GT. 0.000001) GO TO 20 11 X = -X IF (X.LT. 0.000001) GO TO

More information

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

ilist.add(new Integer(1))과 같이 사용하지 않고 ilist.add(1)과 같이 사용한 것은 자바 5.0에 추가된 기본 자료형과 해당 객체 자료 형과의 오토박싱/언박싱 기능을 사용한 것으로 오토박싱이란 자바 컴파일러가 객체를 요구하는 곳에 기본 자료형 바에 제네릭스(generics)를 도입하기 위한 연구는 이미 8년 전인 1996년부터라고 한다. 실제로 자바에 제네릭스를 도입하 는 몇 가지 방안들이 논문으로 나오기 시작한 것이 1998년 초임을 감 안하면 무려 8년이 지난 후에야 자바 5.0에 전격 채택되었다는 것은 이것이 얼마나 어려운 일이었나 하는 것을 보여준다. 자바의 스펙을 결정하는 표준화 절차인

More information

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

예외 예외정의예외발생예외처리예외전파 단정 단정의선언 단정조건검사옵션 2 예외 예외정의예외발생예외처리예외전파 단정 단정의선언 단정조건검사옵션 kkman@sangji.ac.kr 2 예외 (exception) 실행시간에발생하는에러 (run-time error) 프로그램의비정상적인종료잘못된실행결과 예외처리 (exception handling) 기대되지않은상황에대해예외를발생야기된예외를적절히처리 (exception handler) kkman@sangji.ac.kr

More information

Microsoft PowerPoint - lec2.ppt

Microsoft PowerPoint - lec2.ppt 2008 학년도 1 학기 상지대학교컴퓨터정보공학부 고광만 강의내용 어휘구조 토큰 주석 자료형기본자료형 참조형배열, 열거형 2 어휘 (lexicon) 어휘구조와자료형 프로그램을구성하는최소기본단위토큰 (token) 이라부름문법적으로의미있는최소의단위컴파일과정의어휘분석단계에서처리 자료형 자료객체가갖는형 구조, 개념, 값, 연산자를정의 3 토큰 (token) 정의문법적으로의미있는최소의단위예,

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 오류처리 손시운 ssw5176@kangwon.ac.kr 오류메시지를분석한다. 오류메시지에서많은내용을알수있다. 2 디버깅 디버거를사용하면프로그램에서쉽게오류를감지하고진단할수있다. 디버거는중단점을설정하여서프로그램의실행을제어할수있으며문장 단위로실행하거나변수의값을살펴볼수있다. 3 이클립스에서디버깅 4 이클립스에서디버깅 5 이클립스의디버깅명령어 6 예외처리

More information

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍 Power Java 제 11 장상속 이번장에서학습할내용 상속이란? 상속의사용 메소드재정의 접근지정자 상속과생성자 Object 클래스 종단클래스 상속을코드를재사용하기위한중요한기법입니다. 상속이란? 상속의개념은현실세계에도존재한다. 상속의장점 상속의장점 상속을통하여기존클래스의필드와메소드를재사용 기존클래스의일부변경도가능 상속을이용하게되면복잡한 GUI 프로그램을순식간에작성

More information

슬라이드 1

슬라이드 1 UNIT 6 배열 로봇 SW 교육원 3 기 학습목표 2 배열을사용핛수있다. 배열 3 배열 (Array) 이란? 같은타입 ( 자료형 ) 의여러변수를하나의묶음으로다루는것을배열이라고함 같은타입의많은양의데이터를다룰때효과적임 // 학생 30 명의점수를저장하기위해.. int student_score1; int student_score2; int student_score3;...

More information

JAVA PROGRAMMING 실습 02. 표준 입출력

JAVA PROGRAMMING 실습 02. 표준 입출력 자바의기본구조? class HelloJava{ public static void main(string argv[]){ system.out.println( hello,java ~ ){ } } # 하나하나뜯어살펴봅시다! public class HelloJava{ 클래스정의 public static void main(string[] args){ System.out.println(

More information

비긴쿡-자바 00앞부속

비긴쿡-자바 00앞부속 IT COOKBOOK 14 Java P r e f a c e Stay HungryStay Foolish 3D 15 C 3 16 Stay HungryStay Foolish CEO 2005 L e c t u r e S c h e d u l e 1 14 PPT API C A b o u t T h i s B o o k IT CookBook for Beginner Chapter

More information

JAVA PROGRAMMING 실습 02. 표준 입출력

JAVA PROGRAMMING 실습 02. 표준 입출력 # 왜생겼나요..? : 절차지향언어가가진단점을보완하고다음의목적을달성하기위해..! 1. 소프트웨어생산성향상 객체지향소프트웨어를새로만드는경우이미만든개체지향소프트웨어를상속받거나객체를 가져다재사용할수있어부분수정을통해소프트웨어를다시만드는부담줄임. 2. 실세계에대한쉬운모델링 실세계의일은절차나과정보다는일과관련된많은물체들의상호작용으로묘사. 캡슐화 메소드와데이터를클래스내에선언하고구현

More information

10장.key

10장.key JAVA Programming 1 2 (Event Driven Programming)! :,,,! ( )! : (batch programming)!! ( : )!!!! 3 (Mouse Event, Action Event) (Mouse Event, Action Event) (Mouse Event, Container Event) (Key Event) (Key Event,

More information

4장.문장

4장.문장 문장 1 배정문 혼합문 제어문 조건문반복문분기문 표준입출력 입출력 형식화된출력 [2/33] ANSI C 언어와유사 문장의종류 [3/33] 값을변수에저장하는데사용 형태 : < 변수 > = < 식 > ; remainder = dividend % divisor; i = j = k = 0; x *= y; 형변환 광역화 (widening) 형변환 : 컴파일러에의해자동적으로변환

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 @ Lesson 4 (Object) (Class) (Instance) (Method) (Constructor) Memory 1 UML 1 @ & 1 (Real World) (Software World) @ &.. () () @ & 2 (Real World) (Software World) OOA/ Modeling Abstraction Instantiation

More information

untitled

untitled - -, (insert) (delete) - - (insert) (delete) (top ) - - (insert) (rear) (delete) (front) A A B top A B C top push(a) push(b) push(c) A B top pop() top A B D push(d) top #define MAX_STACK_SIZE 100 int

More information

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍 Power Java 제 9 장생성자와접근제어 이번장에서학습할내용 생성자 정적변수 정적메소드 접근제어 this 클래스간의관계 객체가생성될때초기화를담당하는생성자에대하여살펴봅니다. 생성자 생성자 (contructor): 객체가생성될때에필드에게초기값을제공하고필요한초기화절차를실행하는메소드 생성자의예 class Car { private String color; // 색상

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 배효철 th1g@nate.com 1 목차 표준입출력 파일입출력 2 표준입출력 표준입력은키보드로입력하는것, 주로 Scanner 클래스를사용. 표준출력은화면에출력하는메소드를사용하는데대표적으로 System.out.printf( ) 를사용 3 표준입출력 표준출력 : System.out.printlf() 4 표준입출력 Example 01 public static void

More information

PowerPoint Presentation

PowerPoint Presentation 자바프로그래밍 1 클래스와메소드심층연구 ( 실습 ) 손시운 ssw5176@kangwon.ac.kr 예제 1. 접근제어 class A { private int a; int b; public int c; // 전용 // 디폴트 // 공용 public class Test { public static void main(string args[]) { A obj = new

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 상속 배효철 th1g@nate.com 1 목차 상속개념 클래스상속 부모생성자호출 메소드재정의 final 클래스와 final 메소드 protected 접근제한자 타입변환과다형성 추상클래스 2 상속개념 상속 (Inheritance) 이란? 현실세계 : 부모가자식에게물려주는행위 부모가자식을선택해서물려줌 객체지향프로그램 : 자식 ( 하위, 파생 ) 클래스가부모 (

More information

5장.key

5장.key JAVA Programming 1 (inheritance) 2!,!! 4 3 4!!!! 5 public class Person {... public class Student extends Person { // Person Student... public class StudentWorker extends Student { // Student StudentWorker...!

More information

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

(Microsoft PowerPoint - java2-lecture3.ppt [\310\243\310\257 \270\360\265\345]) Class Class, Collections 514770-1 2017 년봄학기 3/22/2017 박경신 클래스 (Class) 객체의속성과행위선언 객체의설계도혹은틀 객체 (Object) 클래스의틀로찍어낸실체 메모리공간을갖는구체적인실체 클래스를구체화한객체를인스턴스 (instance) 라고부름 객체와인스턴스는같은뜻으로사용 클래스구조 클래스접근권한, public 다른클래스들에서이클래스를사용하거나접근할수있음을선언

More information

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx 2018 학년도 1 학기 JAVA 프로그래밍 II 514760-1 2018 년봄학기 5/10/2018 박경신 Lab#1 (ImageTest) Lab#1 은영상파일 (Image) 을읽어서정보를출력 Java Tutorials Lesson: Working with Images https://docs.oracle.com/javase/tutorial/2d/images/index.html

More information

Connection 8 22 UniSQLConnection / / 9 3 UniSQL OID SET

Connection 8 22 UniSQLConnection / / 9 3 UniSQL OID SET 135-080 679-4 13 02-3430-1200 1 2 11 2 12 2 2 8 21 Connection 8 22 UniSQLConnection 8 23 8 24 / / 9 3 UniSQL 11 31 OID 11 311 11 312 14 313 16 314 17 32 SET 19 321 20 322 23 323 24 33 GLO 26 331 GLO 26

More information

교육자료

교육자료 THE SYS4U DODUMENT Java Reflection & Introspection 2012.08.21 김진아사원 2012 SYS4U I&C All rights reserved. 목차 I. 개념 1. Reflection 이란? 2. Introspection 이란? 3. Reflection 과 Introspection 의차이점 II. 실제사용예 1. Instance의생성

More information

PowerPoint Presentation

PowerPoint Presentation public class SumTest { public static void main(string a1[]) { int a, b, sum; a = Integer.parseInt(a1[0]); b = Integer.parseInt(a1[1]); sum = a + b ; // 두수를더하는부분입니다 System.out.println(" 두수의합은 " + sum +

More information

Chap12

Chap12 12 12Java RMI 121 RMI 2 121 RMI 3 - RMI, CORBA 121 RMI RMI RMI (remote object) 4 - ( ) UnicastRemoteObject, 121 RMI 5 class A - class B - ( ) class A a() class Bb() 121 RMI 6 RMI / 121 RMI RMI 1 2 ( 7)

More information

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

1. 자바프로그램기초 및개발환경 2 장 & 3 장. 자바개발도구 충남대학교 컴퓨터공학과 1. 자바프로그램기초 및개발환경 2 장 & 3 장. 자바개발도구 충남대학교 컴퓨터공학과 학습내용 1. Java Development Kit(JDK) 2. Java API 3. 자바프로그래밍개발도구 (Eclipse) 4. 자바프로그래밍기초 2 자바를사용하려면무엇이필요한가? 자바프로그래밍개발도구 JDK (Java Development Kit) 다운로드위치 : http://www.oracle.com/technetwork/java/javas

More information

PowerPoint Presentation

PowerPoint Presentation Class : Method Jo, Heeseung 목차 section 1 생성자 (Constructor) section 2 생성자오버로딩 (Overloading) section 3 예약어 this section 4 메소드 4-1 접근한정자 4-2 클래스메소드 4-3 final, abstract, synchronized 메소드 4-4 메소드반환값 (return

More information

Microsoft PowerPoint - RMI.ppt

Microsoft PowerPoint - RMI.ppt ( 분산통신실습 ) RMI RMI 익히기 1. 분산환경에서동작하는 message-passing을이용한 boundedbuffer 해법프로그램을실행해보세요. 소스코드 : ftp://211.119.245.153 -> os -> OSJavaSources -> ch15 -> rmi http://marvel el.incheon.ac.kr의 Information Unix

More information

PowerPoint Template

PowerPoint Template 10. 예외처리 대구가톨릭대학교 IT 공학부 소프트웨어공학연구실 목차 2 10.1 개요 10.2 C++ 의예외처리 10.3 Java 의예외처리 10.4 Ada 의예외처리 10.1 예외처리의개요 (1) 3 예외 (exception) 오버플로나언더플로, 0 으로나누기, 배열첨자범위이탈오류와같이프로그램실행중에비정상적으로발생하는사건 예외처리 (exception handling)

More information

Microsoft PowerPoint - Chapter 6.ppt

Microsoft PowerPoint - Chapter 6.ppt 6.Static 멤버와 const 멤버 클래스와 const 클래스와 static 연결리스트프로그램예 Jong Hyuk Park 클래스와 const Jong Hyuk Park C 의 const (1) const double PI=3.14; PI=3.1415; // 컴파일오류 const int val; val=20; // 컴파일오류 3 C 의 const (1)

More information

9장.예외와 단정

9장.예외와 단정 예외 예외정의예외발생예외처리예외전파 단정 단정의선언 단정조건검사옵션 [2/28] 예외 (exception) 실행시간에발생하는에러 (run-time error) 프로그램의비정상적인종료잘못된실행결과 예외처리 (exception handling) 기대되지않은상황에대해예외를발생 야기된예외를적절히처리 (exception handler) [3/28] 단정 (assertion)

More information

Microsoft PowerPoint 장강의노트.ppt

Microsoft PowerPoint 장강의노트.ppt 클래스와객체 클래스와객체 객체 : 우리주변의어떤대상의모델 - 예 : 사람, 차, TV, 개 객체 = 상태 (state) + 행동 (behavior) - 예 : 개의상태 - 종자, 이름, 색개의행동 - 짖다, 가져오다 상태는변수로행동은메소드로나타냄 객체는클래스에의해정의된다. 클래스는객체가생성되는틀혹은청사진이다. 2 예 : 클래스와객체 질문 : 클래스와객체의다른예는?

More information

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

Microsoft PowerPoint - 3ÀÏ°_º¯¼ö¿Í »ó¼ö.ppt 변수와상수 1 변수란무엇인가? 변수 : 정보 (data) 를저장하는컴퓨터내의특정위치 ( 임시저장공간 ) 메모리, register 메모리주소 101 번지 102 번지 변수의크기에따라 주로 byte 단위 메모리 2 기본적인변수형및변수의크기 변수의크기 해당컴퓨터에서는항상일정 컴퓨터마다다를수있음 short

More information

JMF3_심빈구.PDF

JMF3_심빈구.PDF JMF JSTORM http://wwwjstormpekr Issued by: < > Revision: Document Information Document title: Document file name: Revision number: Issued by: JMF3_ doc Issue Date:

More information

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

Microsoft PowerPoint - chap02-C프로그램시작하기.pptx #include int main(void) { int num; printf( Please enter an integer "); scanf("%d", &num); if ( num < 0 ) printf("is negative.\n"); printf("num = %d\n", num); return 0; } 1 학습목표 을 작성하면서 C 프로그램의

More information

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

파일로입출력하기II - 파일출력클래스중에는데이터를일정한형태로출력하는기능을가지고있다. - PrintWriter와 PrintStream을사용해서원하는형태로출력할수있다. - PrintStream은구버전으로가능하면 PrintWriter 클래스를사용한다. PrintWriter 파일로입출력하기II - 파일출력클래스중에는데이터를일정한형태로출력하는기능을가지고있다. - PrintWriter와 PrintStream을사용해서원하는형태로출력할수있다. - PrintStream은구버전으로가능하면 PrintWriter 클래스를사용한다. PrintWriter 클래스의사용법은다음과같다. PrintWriter writer = new PrintWriter("output.txt");

More information

6주차.key

6주차.key 6, Process concept A program in execution Program code PCB (process control block) Program counter, registers, etc. Stack Heap Data section => global variable Process in memory Process state New Running

More information

C++ Programming

C++ Programming C++ Programming 상속과다형성 Seo, Doo-okok clickseo@gmail.com http://www.clickseo.com 목 차 상속의이해 상속과다형성 다중상속 2 상속과다형성 객체의이해 상속클래스의객체의생성및소멸 상속의조건 상속과다형성 다중상속 3 상속의이해 상속 (Inheritance) 클래스에구현된모든특성 ( 멤버변수와멤버함수 )

More information

<4D F736F F F696E74202D20C1A63139C0E520B9E8C4A120B0FCB8AEC0DA28B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

<4D F736F F F696E74202D20C1A63139C0E520B9E8C4A120B0FCB8AEC0DA28B0ADC0C729205BC8A3C8AF20B8F0B5E55D> Power Java 제 19 장배치관리자 이번장에서학습할내용 배치관리자의개요 배치관리자의사용 FlowLayout BorderLayout GridLayout BoxLayout CardLayout 절대위치로배치 컨테이너안에서컴포넌트를배치하는방법에대하여살펴봅시다. 배치관리자 (layout manager) 컨테이너안의각컴포넌트의위치와크기를결정하는작업 [3/70] 상당히다르게보인다.

More information

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

Microsoft PowerPoint - additional08.ppt [호환 모드] 8. 상속과다형성 (polymorphism) 상속된객체와포인터 / 참조자의관계 정적바인딩과동적바인딩 virtual 소멸자 Jong Hyuk Park 상속의조건 public 상속은 is-a 관계가성립되도록하자. 일반화 ParttimeStd 구체화 2 상속의조건 잘못된상속의예 현실세계와완전히동떨어진모델이형성됨 3 상속의조건 HAS-A( 소유 ) 관계에의한상속!

More information

<4D F736F F F696E74202D20C1A63234C0E520C0D4C3E2B7C228B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

<4D F736F F F696E74202D20C1A63234C0E520C0D4C3E2B7C228B0ADC0C729205BC8A3C8AF20B8F0B5E55D> Power Java 제 24 장입출력 이번장에서학습할내용 스트림이란? 스트림의분류 바이트스트림 문자스트림 형식입출력 명령어행에서입출력 파일입출력 스트림을이용한입출력에대하여살펴봅시다. 스트림 (stream) 스트림 (stream) 은 순서가있는데이터의연속적인흐름 이다. 스트림은입출력을물의흐름처럼간주하는것이다. 스트림들은연결될수있다. 중간점검문제 1. 자바에서는입출력을무엇이라고추상화하는가?

More information

Cluster management software

Cluster management software 자바네트워크프로그래밍 (OCJP 국제공인자격취득중심 ) 충북대학교최민 교재소개 http://www.forsamsung.co.kr 국제공인자바프로그래머 OCJP 실전가이드 2 예제 1-2-2 프로그램에서메인에서인수전달. public class BankAccount2 { String name; int accountnumber; void setinfo(string

More information

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

작성자 : 김성박\(삼성 SDS 멀티캠퍼스 전임강사\) Session 을이용한현재로그인한사용자의 숫자구하기 작성자 : 김성박 ( 삼성 SDS 멀티캠퍼스전임강사 ) email : urstory@nownuri.net homepage : http://sunny.sarang.net - 본문서는http://sunny.sarang.net JAVA강좌란 혹은 http://www.javastudy.co.kr 의 칼럼 란에서만배포합니다.

More information

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

11 템플릿적용 - Java Program Performance Tuning (김명호기술이사) Java Program Performance Tuning ( ) n (Primes0) static List primes(int n) { List primes = new ArrayList(n); outer: for (int candidate = 2; n > 0; candidate++) { Iterator iter = primes.iterator(); while

More information