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

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

PowerPoint Presentation

PowerPoint 프레젠테이션

PowerPoint Presentation

JAVA PROGRAMMING 실습 08.다형성

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

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

PowerPoint Presentation

PowerPoint Presentation

<4D F736F F F696E74202D20C1A63038C0E520C5ACB7A1BDBABFCD20B0B4C3BC4928B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

PowerPoint Presentation

쉽게 풀어쓴 C 프로그래밍

5장.key

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

제11장 프로세스와 쓰레드

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

Design Issues

PowerPoint Presentation

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

JAVA PROGRAMMING 실습 02. 표준 입출력

Microsoft PowerPoint - Lect04.pptx

Microsoft PowerPoint - 2강

JAVA PROGRAMMING 실습 05. 객체의 활용

쉽게 풀어쓴 C 프로그래밍

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx

PowerPoint Presentation

PowerPoint Presentation

JVM 메모리구조

PowerPoint Presentation

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

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

Chap12

Network Programming

오버라이딩 (Overriding)

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

JAVA PROGRAMMING 실습 02. 표준 입출력

PowerPoint Presentation

05-class.key

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 프로그래밍

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

JMF3_심빈구.PDF

PowerPoint Presentation

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

ch09

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

제8장 자바 GUI 프로그래밍 II

Microsoft PowerPoint - 04-UDP Programming.ppt

Spring Boot/JDBC JdbcTemplate/CRUD 예제

자바 프로그래밍

<4D F736F F F696E74202D205B4A415641C7C1B7CEB1D7B7A1B9D65D35C0E5BBF3BCD3B0FAB4D9C7FCBCBA>

Hanyang Volunteer Corps volunteer image

Microsoft PowerPoint - CSharp-10-예외처리

09-interface.key

PowerPoint 프레젠테이션

슬라이드 1

쉽게 풀어쓴 C 프로그래밍

설계란 무엇인가?

PowerPoint Presentation

교육자료

C++ Programming

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

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

Cluster management software

JAVA PROGRAMMING 실습 07. 상속

PowerPoint Presentation

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

슬라이드 1

JAVA PROGRAMMING 실습 05. 객체의 활용

쉽게 풀어쓴 C 프로그래밍

PowerPoint 프레젠테이션

PowerPoint Presentation

<4D F736F F F696E74202D20C1A63236C0E520BED6C7C3B8B428B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

PowerPoint 프레젠테이션

Cluster management software

gnu-lee-oop-kor-lec10-1-chap10

Microsoft PowerPoint - 14주차 강의자료

Microsoft PowerPoint 장강의노트.ppt

PowerPoint Presentation

C++ Programming

JAVA PROGRAMMING 실습 09. 예외처리

PowerPoint Template

쉽게 풀어쓴 C 프로그래밍

4 장클래스와객체 클래스와객체 public과 private 구조체와클래스객체의생성과생성자객체의소멸과소멸자생성자와소멸자의호출순서디폴트생성자와디폴트소멸자멤버초기화멤버함수의외부정의멤버함수의인라인함수선언 C++ 프로그래밍입문

No Slide Title

쉽게 풀어쓴 C 프로그래밍

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

Contents. 1. PMD ㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍ 2. Metrics ㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍ 3. FindBugs ㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍ 4. ㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍㆍ

ThisJava ..

Microsoft PowerPoint - Chapter 6.ppt

PowerPoint 프레젠테이션

C# Programming Guide - Types

1

Microsoft PowerPoint - 5장

Microsoft PowerPoint - Chap12-OOP.ppt

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

Transcription:

실세계의인터페이스와인터페이스의필요성 인터페이스, 람다식 514760-1 2017 년가을학기 10/2/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 static final 자동적으로컴파일과정에서붙음 상수명은대문자로작성 서로다른단어로구성되어있을경우에는언더바 (_) 로연결 선언과동시에초기값지정 static { 블록작성불가 - static { 으로초기화불가 interface Days { public static final int SUNDAY = 1, MONDAY = 2, TUESDAY = 3, WEDNESDAY = 4, THURSDAY = 5, FRIDAY = 6, SATURDAY = 7; 추상메소드 (abstract method) 선언 인터페이스통해호출된메소드는최종적으로객체에서실행 인터페이스의메소드는기본적으로실행블록이없는추상메소드로선언 public abstract 를생략하더라도자동적으로컴파일과정에서붙게됨 디폴트메소드 (default method) 선언 자바 8 에서추가된인터페이스의새로운멤버 인스턴스메소드와동일하게실행블록을가지고있는메소드 default 키워드를반드시붙여야함 기본적으로 public 접근제한 생략하더라도컴파일과정에서자동붙음 interface MyInterface { public void mymethod1(); default void mymethod2() { System.out.println("myMethod2()");

정적메소드 (static method) 선언 자바8에서추가된인터페이스의새로운멤버 static 키워드를반드시붙여야함 interface MyInterface { static void print(string msg) { System.out.println(msg + ": 인터페이스의정적메소드호출 "); public class StaticMethodTest { MyInterface.print("Java 8"); 사례 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 { 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 { 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 인터페이스구현 익명구현객체 명시적인구현클래스작성생략하고바로구현객체를얻는방법 이름없는구현클래스선언과동시에객체생성 인터페이스의다중구현 다중인터페이스 (multi-interface) 구현클래스 구현클래스는다수의인터페이스를모두구현 객체는다수의인터페이스타입으로사용 인터페이스의추상메소드들을모두재정의하는실체메소드가있어야 추가적으로필드와메소드선언가능하나익명객체안에서만사용 인터페이스변수로접근불가 public class RemoteControlExample { RemoteControl rc = new RemoteControl() { // anonymous class public void turnon() { /* 실행문 */ public void turnoff() { /* 실행문 */ public void setvolume(int volume) { /* 실행문 */ ; 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;

Comparable 인터페이스 public Object findlargest(object object1, Object object2) { Comparable obj1 = (Comparable)object1; Comparable obj2 = (Comparable)object2; if ((obj1).compareto(obj2) > 0) return object1; else return object2; 예제 : 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; 예제 : Comparable 인터페이스 public class RectangleTest { 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 (p1.age == p2.age) return 0; else if (p1.age > p2.age) return 1; else return -1;

Enumeration 인터페이스 Enumeration 인터페이스는객체들의집합 (Vector) 에서각각의객체들을순차적으로처리할수있는메소드를제공하는인터페이스 Enumeration 객체는 new 연사자로생성할수없으며, Vector 를이용하여생성할수있다. Vector 클래스의 elements() 라는메소드는객체의모든요소들을 Enumeration 객체로반환한다. public interface Enumeration { // Vector 로부터생성된 Enumeration 요소가있으면 true, 아니면 false boolean hasmoreelements(); // 다음 Enumeration 요소를반환 Object nextelement(); 예제 : Enumeration 인터페이스 public class EnumerationTest { Vector<String> v1 = new Vector<String>(); v1.addelement( ABC ); v1.addelement( DEF"); v1.addelement( GHI"); for(int i=0; i<v1.size(); i++){ System.out.println("v1["+i+"]="+v1.elementAt(i)); Enumeration<String> e = v1.elements(); while(e.hasmoreelements()){ System.out.println("e="+e.nextElement()); ActionListener 인터페이스 ActionListener 인터페이스는자바의이벤트리스너 ( 이벤트를처리하는인터페이스 ) 중하나로, 사용자가 Action 을했을시 Action 이벤트를발생시키는인터페이스 public interface ActionListener { // 액션이벤트가발생할때호출된다. void actionperformed(actionevent other); 예제 : ActionListener 인터페이스 class MyClass implements ActionListener { public void actionperformed(actionevent event) { System.out.println(""); public class CallbackTest { ActionListener listener = new MyClass(); Timer t = new Timer(1000, listener); t.start(); for (int i = 0; i < 1000; i++) { try { Thread.sleep(1000); catch (InterruptedException e) { // 1 초에한번씩 출력

람다식 람다식 (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; ; 예제 : 람다식사용 import javax.swing.timer; public class CallbackTest { Timer t = new Timer(1000, event -> System.out.println("")); t.start(); for (int i = 0; i < 1000; i++) { try { Thread.sleep(1000); catch (InterruptedException e) { // 1초에한번씩 출력 함수인터페이스와람다식 함수인터페이스는하나의추상메서드만선언된인터페이스, 예 : java.lang.runnable 람다식은함수인터페이스에대입할수있다. Runnable r = () -> System.out.println(" 스레드가실행되고있습니다.");

예제 : 함수인터페이스 람다식을사용한 sort @FunctionalInterface interface MyInterface { void sayhello(); public class LambdaTest1 { MyInterface hello = () -> System.out.println("Hello Lambda!"); hello.sayhello(); 무명클래스를사용한방식 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()); ; Hello Lambda! 람다식을사용한 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) );