Microsoft PowerPoint - java2-lecture4.ppt [호환 모드]

Similar documents
Microsoft PowerPoint - java1-lecture6.ppt [호환 모드]

Microsoft PowerPoint - java1-lecture6.ppt [호환 모드]

JAVA PROGRAMMING 실습 08.다형성

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

PowerPoint Presentation

PowerPoint 프레젠테이션

Microsoft PowerPoint - java2-lecture3.ppt [호환 모드]

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

Microsoft PowerPoint - java1-lecture8.ppt [호환 모드]

Microsoft PowerPoint - java1-lecture8.ppt [호환 모드]

Microsoft PowerPoint - java1-lecture8.ppt [호환 모드]

슬라이드 1

PowerPoint Presentation

PowerPoint Presentation

PowerPoint Presentation

PowerPoint Presentation

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

5장.key

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

<4D F736F F F696E74202D20C1A63038C0E520C5ACB7A1BDBABFCD20B0B4C3BC4928B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

쉽게 풀어쓴 C 프로그래밍

PowerPoint Presentation

JAVA PROGRAMMING 실습 05. 객체의 활용

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

PowerPoint 프레젠테이션

PowerPoint Presentation

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

Microsoft PowerPoint - 2강

Design Issues

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

gnu-lee-oop-kor-lec11-1-chap15

JAVA PROGRAMMING 실습 02. 표준 입출력

Microsoft PowerPoint - java1-lecture6.ppt [호환 모드]

(8) getpi() 함수는정적함수이므로 main() 에서호출할수있다. (9) class Circle private double radius; static final double PI= ; // PI 이름으로 로초기화된정적상수 public

05-class.key

PowerPoint Presentation

PowerPoint Presentation

JAVA PROGRAMMING 실습 02. 표준 입출력

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx

PowerPoint 프레젠테이션

A Tour of Java V

쉽게 풀어쓴 C 프로그래밍

Microsoft PowerPoint - Lect04.pptx

Microsoft Word - java19-1-midterm-answer.doc

쉽게 풀어쓴 C 프로그래밍

PowerPoint 프레젠테이션

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

쉽게 풀어쓴 C 프로그래밍

제11장 프로세스와 쓰레드

PowerPoint Presentation

PowerPoint Presentation

untitled

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

PowerPoint 프레젠테이션

Spring Boot/JDBC JdbcTemplate/CRUD 예제

자바 프로그래밍

No Slide Title

PowerPoint Presentation

PowerPoint Presentation

오버라이딩 (Overriding)

Microsoft PowerPoint - Lect07.pptx

C# Programming Guide - Types

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

교육자료

PowerPoint 프레젠테이션

JVM 메모리구조

java.lang 패키지 java.util 패키지 java.io 패키지 콜렉션 2

<4D F736F F F696E74202D205B4A415641C7C1B7CEB1D7B7A1B9D65D35C0E5BBF3BCD3B0FAB4D9C7FCBCBA>

chap 5: Trees

PowerPoint Presentation

Microsoft PowerPoint - lec12 [호환 모드]

rmi_박준용_final.PDF

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

JAVA PROGRAMMING 실습 05. 객체의 활용

JAVA PROGRAMMING 실습 09. 예외처리

A Tour of Java IV

선형대수학 Linear Algebra

항상쌍 ( 키, 값 ) 으로만데이터를저장하는클래스 의최고조상 : Map - Map을조상으로하는클래스, HashTable, HashMap, LinkedHashMap, TreeMap 등은데이터를저장할때반드시 키 와 값 의쌍으로저장한다. - Map에저장되는 키 는중복되면안되

Microsoft PowerPoint 장강의노트.ppt

PowerPoint 프레젠테이션

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

12-file.key

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

JAVA PROGRAMMING 실습 07. 상속

쉽게 풀어쓴 C 프로그래밍

슬라이드 1

Microsoft PowerPoint - 6주차.pptx

슬라이드 1

슬라이드 1

Microsoft PowerPoint - C++ 5 .pptx

PowerPoint Presentation

1. 객체의생성과대입 int 형변수 : 선언과동시에초기화하는방법 (C++) int a = 3; int a(3); // 기본타입역시클래스와같이처리가능 객체의생성 ( 복습 ) class CPoint private : int x, y; public : CPoint(int a

chap10.PDF

Network Programming

슬라이드 1

<4D F736F F F696E74202D2036C0CFC2B05FB0B4C3BCC1F6C7E2C7C1B7CEB1D7B7A1B9D62E707074>

Microsoft PowerPoint - 04-UDP Programming.ppt

PowerPoint 프레젠테이션

슬라이드 1

Transcription:

인터페이스의필요성 Interface, Collections, Lambda 514770-1 2017 년가을학기 3/29/2017 박경신 인터페이스를이용하여다중상속구현 자바에서클래스다중상속불가 인터페이스는명세서와같음 인터페이스만선언하고구현을분리하여, 작업자마다다양한구현을할수있음 사용자는구현의내용은모르지만, 인터페이스에선언된메소드가구현되어있기때문에호출하여사용하기만하면됨 110v 전원아울렛처럼규격에맞기만하면, 어떻게만들어졌는지알필요없이전원연결에사용하기만하면됨 사용자 인터페이스 구현 1 구현 2 자바의인터페이스 인터페이스 (interface) 모든메소드가추상메소드인클래스 인터페이스선언 interface 키워드로선언 ex) public interface SerialDriver { 인터페이스의특징 인터페이스의메소드 public abstract 타입으로생략가능 인터페이스의상수 public static final 타입으로생략가능 인터페이스의객체생성불가 인터페이스에대한레퍼런스변수는선언가능 인터페이스선언 인터페이스구성멤버 상수필드 (constant field) 추상메소드 (abstract method) 디폴트메소드 (default method) 정적메소드 (static method) public interface 인터페이스명 { // 상수 (constant fields) 타입상수명 = 값 ; // 추상메소드 (abstract method) 리턴타입메소드명 ( 매개변수,..); // 디폴트메소드 (default method) default 리턴타입메소드명 ( 매개변수,..) {.. 내부구현.. // 정적메소드 (static method) static 리턴타입메소드명 ( 매개변수,..) {.. 내부구현..

인터페이스선언 public interface RemoteControl { int MAX_VOLUME = 10; // 상수 (constant fields) int MIN_VOLUME = 0; // 상수 (constant fields) // 추상메소드 (abstract method) void turnon(); void turnoff(); void setvolume(int volume); // 디폴트메소드 (default method) default void setmute(boolean mute) { if(mute) System.out.println(" 무음처리합니다."); else System.out.println(" 무음해제합니다."); // 정적메소드 (static method) static void changebattery() { System.out.println(" 건전지를교환합니다."); 인터페이스상속 인터페이스간에도상속가능 인터페이스를상속하여확장된인터페이스작성가능 인터페이스다중상속허용 interface MobilePhone { boolean sendcall(); boolean receivecall(); boolean sendsms(); boolean receivesms(); interface MP3 { void play(); void stop(); interface MusicPhone extends MobilePhone, MP3 { void playmp3ringtone(); public class MyPhone implements MusicPhone { public boolean sendcall() { ; public boolean receivecall() { ; public boolean sendsms() { ; public boolean receivesms() {.; public void play() {..; public void stop() {.; void playmp3ringtone() {.; 인터페이스구현 구현클래스정의 자신의객체가인터페이스타입으로사용할수있음 implements 키워드사용 여러개의인터페이스동시구현가능 상속과구현이동시에가능 public class 클래스명 implements 인터페이스명 { // 인터페이스에선언된추상메소드의실체메소드구현 추상메소드의실체메소드를작성하는방법 메소드의선언부가정확히일치해야함 인터페이스의모든추상메소드를재정의하는실체메소드를작성해야함 일부추상메소드만재정의할경우, 구현클래스는추상클래스 인터페이스구현및사용 public class Television implements RemoteControl { private int volume; // 필드 //turnon() 추상메소드의구현 public void turnon() { System.out.println("TV를켭니다."); //turnoff() 추상메소드의구현 public void turnoff() { System.out.println("TV를끕니다."); //setvolume() 추상메소드의구현 public void setvolume(int volume) { if(volume>remotecontrol.max_volume) { this.volume = RemoteControl.MAX_VOLUME; else if(volume<remotecontrol.min_volume) { this.volume = RemoteControl.MIN_VOLUME; else { this.volume = volume; System.out.println(" 현재 TV 볼륨 : " + volume); public class RemoteControlExample { public static void main(string[] args) { RemoteControl rc; rc = new Television(); rc = new Audio(); // 구현객체 // 구현객체

인터페이스구현및사용 public class Audio implements RemoteControl { private boolean mute; // 필드 @Override // 필요시디폴트메소드재정의 public void setmute(boolean mute) { this.mute = mute; if(mute) { System.out.println("Audio 무음처리합니다."); else { System.out.println("Audio 무음해제합니다."); public class RemoteControlExample { public static void main(string[] args) { RemoteControl rc = null; rc = new Television(); rc.turnon(); // use abstract method rc.setmute(true); // use default method rc = new Audio(); rc.turnon(); // use abstract method rc.setmute(true); // use default method RemoteControl.changeBattery(); // use static method 인터페이스구현 익명구현객체 명시적인구현클래스작성생략하고바로구현객체를얻는방법 이름없는구현클래스선언과동시에객체생성 인터페이스명변수 = new 인터페이스명 () { // 인터페이스에선언된추상메소드의실체메소드구현 인터페이스의추상메소드들을모두재정의하는실체메소드가있어야 추가적으로필드와메소드선언가능하나익명객체안에서만사용 인터페이스변수로접근불가 public class RemoteControlExample { public static void main(string[] args) { RemoteControl rc = new RemoteControl() { // anonymous class public void turnon() { /* 실행문 */ public void turnoff() { /* 실행문 */ public void setvolume(int volume) { /* 실행문 */ ; 인터페이스의다중구현 다중인터페이스 (multi-interface) 구현클래스 구현클래스는다수의인터페이스를모두구현 객체는다수의인터페이스타입으로사용 public class 클래스명 implements 인터페이스명 A, 인터페이스명 B { // 인터페이스 A 에선언된추상메소드의실체메소드구현 // 인터페이스 B 에선언된추상메소드의실체메소드구현 인터페이스의다중구현 interface USBMouseInterface { void mousemove(); void mouseclick(); interface RollMouseInterface { void roll(); public class MouseDriver implements RollMouseInterface, USBMouseInterface { public void mousemove() {... public void mouseclick() {... public void roll() {... // 추가적으로다른메소드를작성할수있다. int getstatus() {... int getbutton() {...

인터페이스사용 인터페이스의사용 클래스의필드 (field) 생성자또는메소드의매개변수 (parameter) 생성자또는메소드의로컬변수 (local variable) MyClass mc = new MyClass( new public class MyClass { Television() ); // field RemoteControl rc = new Television(); // constructor parameter MyClass(RemoteControl rc) { this.rc = rc; // method public method() { // local variable RemoteControl rc = new Audio(); Comparable 인터페이스 Comparable 인터페이스는객체의비교를위한인터페이스로객체간의순서나정렬을하기위해서사용 public interface Comparable { // 이객체가다른객체보다크면 1, 같으면 0, 작으면 -1 을반환한다. int compareto(object other); class Person implements Comparable { public int compareto(object other) { Person p = (Person)other; if (this.age == p.age) return 0; else if (this.age > p.age) return 1; else return -1; Ex : Comparable 인터페이스 Ex : Comparable 인터페이스 public class Rectangle implements Comparable { public int width = 0; public int height = 0; @Override public String tostring() { return "Rect [w=" + width + ", h=" + height + "]"; public Rectangle(int w, int h) { width = w; height = h; System.out.println(this); public int getarea() { return width * height; @Override public int compareto(object other) { Rectangle otherrect = (Rectangle)other; if (this.getarea() < otherrect.getarea()) return -1; else if (this.getarea() > otherrect.getarea()) return 1; else return 0; public class RectangleTest { public static void main(string[] args) { Rectangle r1 = new Rectangle(100, 30); Rectangle r2 = new Rectangle(200, 10); int result = r1.compareto(r2); if (result == 1) System.out.println(r1 + " 가더큽니다."); else if (result == 0) System.out.println(" 같습니다 "); else System.out.println(r2 + " 가더큽니다.");

Comparator 인터페이스 Comparator 인터페이스는다른두개의객체를비교하기위한인터페이스 public interface Comparator { // o1가 o2보다크면 1, 같으면 0, 작으면 -1을반환한다. int compare(object o1, Object o2); class AgeComparator implements Comparator { public int compare(object o1, Object o2) { Person p1 = (Person)o1; Person p2 = (Person)o2; if (s1.age == s2.age) return 0; else if (s1.age > s2.age) return 1; else return -1; 컬렉션 (collection) 의개념 컬렉션 요소 (element) 라고불리는가변개수의객체들의저장소 객체들의컨테이너라고도불림 요소의개수에따라크기자동조절 요소의삽입, 삭제에따른요소의위치자동이동 고정크기의배열을다루는어려움해소 다양한객체들의삽입, 삭제, 검색등의관리용이 컬렉션인터페이스와클래스 Collection<E> Map<K, V> Set<E> List<E> Queue<E> 인터페이스 클래스 HashSet<E> ArrayList<E> Vector<E> LinkedList<E> HashMap<K, V> Stack<E> Collection 인터페이스메소드 Method Description boolean add(object element) is used to insert an element in this collection. boolean addall(collection c) is used to insert the specified collection elements in the coll ection. boolean remove(object element) is used to delete an element from this collection. boolean removeall(collection c) is used to delete all the elements of specified collection fro m the collection. boolean retainall(collection c) is used to delete all the elements of invoking collection exce pt the specified collection. int size() return the total number of elements in the collection. void clear() removes the total no of element from the collection. boolean contains(object element) is used to search an element. boolean containsall(collection c) is used to search the specified collection in this collection. Iterator iterator() returns an iterator. Object[] toarray() converts collection into array. boolean isempty() checks if collection is empty. boolean equals(object element) matches two collection. int hashcode() returns the hashcode number for collection.

List 인터페이스메소드 Method Description void add(int index, Object elemen is used to insert an element into the list at index passed in t t) he index. boolean addall(int index, Collecti on c) is used to insert all elements of c into the list at the index p assed in the index. object get(int index) is used to return the object stored at the specified index wit hin the collection. object set(int index, Object eleme is used to assign element to the location specified by index nt) within the list. object remove(int index) is used to delete all the elements of invoking collection exce pt the specified collection. ListIterator listiterator() is used to return an iterator to the start of the list. ListIterator listiterator(int index) is used to return an iterator to the list that begins at the sp ecified index. 컬렉션과제네릭 컬렉션은제네릭 (Generics) 기법으로구현됨 컬렉션의요소는객체만가능 기본적으로 int, char, double 등의기본타입사용불가 JDK 1.5 부터자동박싱 / 언박싱기능으로기본타입사용가능 제네릭 (Generics) 특정타입만다루지않고, 여러종류의타입으로변신할수있도록클래스나메소드를일반화시키는기법 <E>, <K>, <V> : 타입매개변수 요소타입을일반화한타입 제네릭클래스사례 제네릭벡터 : Vector<E> E 에특정타입으로구체화 정수만다루는벡터 Vector<Integer> 문자열만다루는벡터 Vector<String> 컬렉션과자동박싱 / 언박싱 JDK 1.5 이전 기본타입데이터를 Wrapper 클래스를이용하여객체로만들어사용 Vector<Integer> v = new Vector<Integer>(); v.add(new Integer(4)); 컬렉션으로부터요소를얻어올때, Wrapper 클래스로캐스팅필요 Integer n = (Integer)v.get(0); int k = n.intvalue(); // k = 4 JDK 1.5부터 자동박싱 / 언박싱이작동하여기본타입값사용가능 Vector<Integer> v = new Vector<Integer> (); v.add(4); // 4 new Integer(4) 로자동박싱 int k = v.get(0); // Integer 타입이 int 타입으로자동언박싱, k = 4 제네릭의타입매개변수를기본타입으로구체화할수는없음 Vector<int> v = new Vector<int> (); // 오류 Vector<E> Vector<E> 의특성 java.util.vector <E> 에서 E 대신요소로사용할특정타입으로구체화 여러객체들을삽입, 삭제, 검색하는컨테이너클래스 배열의길이제한극복 원소의개수가넘쳐나면자동으로길이조절 Vector 에삽입가능한것 객체, null 기본타입은박싱 / 언박싱으로 Wrapper 객체로만들어저장 Vector 에객체삽입 벡터의맨뒤에객체추가 벡터중간에객체삽입 Vector 에서객체삭제 임의의위치에있는객체삭제가능 : 객체삭제후자동자리이동

Vector<E> 클래스의주요메소드 ArrayList<E> ArrayList<E> 의특성 java.util.arraylist, 가변크기배열을구현한클래스 <E> 에서 E 대신요소로사용할특정타입으로구체화 ArrayList 에삽입가능한것 객체, null 기본타입은박싱 / 언박싱으로 Wrapper 객체로만들어저장 ArrayList 에객체삽입 / 삭제 리스트의맨뒤에객체추가 리스트의중간에객체삽입 임의의위치에있는객체삭제가능 벡터와달리스레드동기화기능없음 다수스레드가동시에 ArrayList 에접근할때동기화되지않음 개발자가스레드동기화코드작성 ArrayList<E> 클래스의주요메소드 HashMap<K,V> HashMap<K,V> 키 (key) 와값 (value) 의쌍으로구성되는요소를다루는컬렉션 java.util.hashmap K는키로사용할요소의타입, V는값으로사용할요소의타입지정 키와값이한쌍으로삽입 키는해시맵에삽입되는위치결정에사용 값을검색하기위해서는반드시키이용 삽입및검색이빠른특징 요소삽입 : put() 메소드 요소검색 : get() 메소드 예 ) HashMap<String, String> 생성, 요소삽입, 요소검색 HashMap<String, String> h = new HashMap<String, String>(); h.put("apple", " 사과 "); // "apple" 키와 " 사과 " 값의쌍을해시맵에삽입 String kor = h.get("apple"); // "apple" 키로값검색. kor 는 " 사과

HashMap<K,V> 의주요메소드 LinkedList<E> LinkedList<E> 의특성 java.util.linkedlist E 에요소로사용할타입지정하여구체와 List 인터페이스를구현한컬렉션클래스 Vector, ArrayList 클래스와매우유사하게작동 요소객체들은양방향으로연결되어관리됨 요소객체는맨앞, 맨뒤에추가가능 요소객체는인덱스를이용하여중간에삽입가능 맨앞이나맨뒤에요소를추가하거나삭제할수있어스택이나큐로사용가능 컬렉션순차검색을위한 Iterator 인터페이스 Iterator<E> 인터페이스 Vector<E>, ArrayList<E>, LinkedList<E> 가상속받는인터페이스 리스트구조의컬렉션에서요소의순차검색을위한메소드포함 Iterator<E> 인터페이스메소드 컬렉션의순차검색을위한 Iterator Vector<Integer> v = new Vector<Integer>(); Iterator<Integer> it = v.iterator(); while(it.hasnext()) { // 모든요소방문 int n = it.next(); // 다음요소리턴... 또는 iterator() 메소드 iterator() 를호출하면 Iterator 객체반환 Iterator 객체를이용하여인덱스없이순차적검색가능 for (int n : v) {

Custom 클래스에대한 sort 메소드사용 개인적으로만든클래스에대해서컬렉션에추가하고, Collections.sort 기능을이용해서정렬하고싶다면 java.lang.comparable 인터페이스를구현해주어야함 public interface Comparable<T> { int compareto(t o); CompareTo(T o) 메소드는현객체를인자로주어진 o 와비교해서순서를정한후에정수 (int) 값을반환함 만약현객체가주어진인자보다작다면음수를반환 만약현객체가주어진인자와동일하다면 0 을반환 만약현객체가주어진인자보다크다면양수를반환 Custom 클래스에대한 sort 메소드사용 import java.util.collections; class A implements java.lang.comparable<a> { int num; String s; public A(String s, int n) { this.s = s; num = n; public int compareto(a a) { if (s.compareto(a.s) == 0) { if (num > a.num) return 1; else if (num < a.num) return -1; else return 0; else { return s.compareto(a.s); public String tostring() { return "String: " + s + "\t num = " + num; 람다식 람다식 (lambda expression) 은나중에실행될목적으로다른곳에전달될수있는코드블록이다. 람다식을이용하면메소드가필요한곳에간단히메소드를보낼수있다. 람다식의구문 람다식은 (argument-list) -> {body 구문사용하여작성 람다식의예 () -> System.out.println("Hello World"); (String s) -> { System.out.println(s); () -> 69 () -> { return 3.141592; ; (String s) -> { return Hello, + s; ;

람다식을사용한 sort 무명클래스를사용한방식 Comparator<Person> byname = new Comparator<Person>() { @Override public int compare(person o1, Person o2) { return o1.getname().compareto(o2.getname()); ; 람다식를사용한방식 Comparator<Person> byname = (Person o1, Person o2) -> o1.getname().compareto(o2.getname()); ; 람다식을사용한 sort 무명클래스를사용한방식 List<Person> plist = getpersonlist(); // sort by age plist.sort(new Comparator<Person>() { @Override public int compare(person o1, Person o2) { return o1.getage() - o2.getage(); ); 람다식을사용한방식 // sort by age plist.sort( (Person o1, Person o2) -> o1.getage() - o2.getage() ); plist.foreach( (person) -> System.out.println(person) );