레이블이 자바 컴포지션인 게시물을 표시합니다. 모든 게시물 표시
레이블이 자바 컴포지션인 게시물을 표시합니다. 모든 게시물 표시

2013년 10월 29일 화요일

Java Colection,AbstractCollection 인터페이스 1. Collection 객체의 모임이며

Java Colection,AbstractCollection 인터페이스

1. Collection
 
객체의 모임이며, 직접 구현 안하며 Set이나 List중 하나를 구현한다.
크기 정보 추출
int size()
boolean isEmpty()
검색, 비교, 복사
boolean contains(Object o)
boolean containsAll(Collection c)
Iterator iterator()
Object[] toArray() : Collection 내의 객체의 배열을 반환
Object[] toArray(Object[] a)
객체 추가, 제거
boolean add(Object o)
boolean addAll(Collection c)
boolean remove(Object o)
boolean removeAll(Collection c) : c를 모두 제거
boolean retainAll(Collection c) : c를 제외한 객체 제거
clear()
특징
구성원 객체의 수가 변경되었으면 true를 반환
허용하지 않는 메쏘드는 UnsupportedOperationException 발생
add, addAll 메쏘드는 ClassCastException 발생 가능
null을 허용하지 않을 경우 NullPointerException 발생 가능
조건에 맞지 않을 경우 IllegalArgumentException 발생 가능
 
2. AbstractCollection
 
Collection 인터페이스 구현한 추상클래스
중복 허용
실제 저장 구조와 관계된 함수는 미구현
변경 불가능한 하위 Collection 구현 시 iterator(), size() 만 구현
변경 가능한 하위 Collection 구현 시
add() 구현하지 않으면  UnsupporedOperationException 발생
String toString()은 각 구성원 객체의 toString() 값을 출력한다.
 
 
[예제]

package onj;
 
//AbstractCollection을 상속한 사용자 정의 컬렉션
import java.util.*;
public class MyCollection extends AbstractCollection {
 private int size = 0;
 private Object[] arr = new Object[10];
 public int size() {
  return size;
 }
 public boolean add(Object o) {
  arr[size++] = o;
  return true;
 }
 public Iterator iterator() {
  return new Iterator() {
   private int current = -1;
   public boolean hasNext() {
    return current + 1 < size;
   }
   public Object next() {
    current++;
    if (size <= current)
     throw new NoSuchElementException();
    return arr[current];
   }
   public void remove() {
    if (current == -1 || size <= current) throw new NoSuchElementException();
    for (int i = current + 1; i < size; i++)
     arr[i - 1] = arr[i];
    current--;
    size--;
   }
  };
 }
 public static void main(String[] args) {
  MyCollection col = new MyCollection();
  col.add("OnJ1");
  col.add("OnJ2");
  System.out.println("size(): " + col.size());
  System.out.println("contains(): " + col.contains("second"));
  System.out.println("toString(): " + col);
  System.out.print("iterator: ");
  // 반복자
  Iterator iter = col.iterator();
  while (iter.hasNext()) {
   System.out.print(iter.next() + ", ");
  }
  System.out.println();
  System.out.print("toArray(): ");
  Object[] array = col.toArray();
  for (int i = 0; i < array.length; i++)
   System.out.print(array[i] + ", ");
  System.out.println();
  col.remove("first");
  System.out.println("remove(): " + col);
  MyCollection col2 = new MyCollection();
  col2.add("OnJ3");
  col2.add("OnJ4");
  System.out.println("containsAll(): " + col.containsAll(col2));
  col.addAll(col2);
  System.out.println("addAll(): " + col);
  col.removeAll(col2);
  System.out.println("removeAll(): " + col);
  col.clear();
  System.out.println("col.size() : " + col.size());
  System.out.println("clear(): " + col);
 }
}
 

[결과]
 
size(): 2
contains(): false
toString(): [OnJ1, OnJ2]
iterator: OnJ1, OnJ2,
toArray(): OnJ1, OnJ2,
remove(): [OnJ1, OnJ2]
containsAll(): false
addAll(): [OnJ1, OnJ2, OnJ3, OnJ4]
removeAll(): [OnJ1, OnJ2]
col.size() : 0
clear(): []

2013년 10월 27일 일요일

[JAVA다향성재정의]자바 다형성(java polymorphism), 메소드재정의, 다중정의(method overrding, method overloading)

[JAVA다향성재정의]자바 다형성(java polymorphism), 메소드재정의, 다중정의(method overrding, method overloading)
 
1. 다형성이란?
 
서로 다른 객체가 같은 메시지에 대하여 서로 다른 방법으로 응답할 수 있는 기능을 이야기 한다.
의미(semantics)는 하나지만 실제 형태는 여러 가지가 될 수 있다는 말이다. 예를 들면, "열다"는 우리는 충분히 이해할 수 있다. 그러나, 실제적으로 "여는 형태"는 많다. 창문을 여는 형태, 강의실 문을 여는 형태, 현관 문을 여는 형태 등 의미는 하나지만 실제적인 형태는 상당히 많을 수 있는 것이다. 
다형성은 프로그램에서 특별한 연산자나 키워드가 있는 것이 아니며 객체지향 프로그래밍 언어에서 "오버로딩 (overloading)", "오버라이딩 (overriding)"의 형태로 나타난다. 
상위 클래스에 정의된 메소드와 동일한 형태의 메소드를 하위 클래스에 정의
동적 메소드 바인딩에 기반한다.
동적 메소드 바인딩에는 어떤 메소드를 호출할 지 컴파일 시 지정하지 않고 실행  시에 동적으로 결정된다.
코드에는 호출할 주소가 아닌, 어떤 메소드를 호출해야 하는지 전체 이름이 적혀있고 JVM은 이걸 보고 힙영역의 객체를 뒤져 적절한 메소드를 호출한다.
그러므로 어느 객체의 어느 메소드가 호출될 지 컴파일 시에는 알 수 없고 단지 타입 정보에만 의존하여 에러 체킹을 한다.
상위 클래스의 일부 메서드가 하위 클래스에 적합하지 않을 경우 하위 클래스에서 해당 메서드만 재정의
추상클래스 등에서 상속받는 모든 하위클래스에서 반드시  정의해야되는 메서드에 대해 그 프로토타입 만을 추상 메서드로 정의하고 이를 상속하는 클래스에서 메서드 재정의
재사용 가능한 강력한 인터페이스 구축
메서드 오버라이딩되면 Super 클래스의 메서드가 가려지게되고 이 경우 super를 사용하면 Super클래스의 메서드를 사용
 
2. method overriding(메서드 재정의) 규약

인스턴스 메서드일 것(static붙어 있는 메소드는 안된다.)
메서드의 이름, 매개변수개구, 매개변수타입, 리턴형이 일치 할 것
메서드의 접근 제어자가 public 또는 protected 일것
protected : 하위 클래스에서 호출하거나, 오버라이드 할 수 있는 접근제어자. 하위 클래스가 아닌 다른 클래스는 호출하지 못한다.
private 일 경우 재정의 할 수 있다.
 
3. 메소드 중복정의, 다중정의(method overloading)

동일한 클래스 내에서 같은 이름의 메소드를 중복  정의하여 다형성을 지원
메서드 이름은 동일하나 매개변수의 TYPE, 매개변수의 개수가 다를 것
 
4. 메소드 재정의 (method overriding)

상속 관계에 있는 클래스간에 메소드를 중복 정의하여 다형성을 지원
즉, 메소드 오버라이딩을 이용하면 하위 클래스에서 동일 이름의 메소드를 새롭게 정의 가능
매개변수의 형이나 매개변수의 수 모두 동일해야 함

5. 다형성의 개념이 적용되는 곳
 
상속(Inheritance)
중복(다중)정의(Overloading)
재정의(Overriding)
Upcasting(상위클래스로 형변환)
Abstract의 상속과 Interface의 구현
 

[예제]
상속과 메소드 재정의를 이용한 다형성
 
class DrawObj {
 void draw() {}
}
class Circle extends DrawObj {
 void draw() {
  System.out.println("원을 그립니다.");
 }
}
class Line extends DrawObj {
 void draw() {
  System.out.println("선을 그립니다.");
 }
}
......
......
......
DrawObj[] objs = new DrawObj[10];
Objs[0] = new Circle();
Objs[1] = new Line();
Objs[2] = new PolyLine();
Objs[3] = new Rectangle();
. . .
Objs[9] = new Line();
//각 draw메소드가 Circle, Line..에 따라 다르게 표현된다.
for(int i = 0; i < objs.length; i++)
    objs[i].draw();

2013년 10월 22일 화요일

[자바상속컴포지션]Java Inheritance & Composition 상속과 컴포지션은 동전의 양면과 같이 유사하게 서로에게 관련이 있다. 상속은 마치 양파가 여러 껍질로 이루어진 것과 같이 계층화된 객체 컴포지션은 여러 재료(객체)가 한데 뭉쳐서 만들어진 죽 컴포지션은 개체들간의 'has a' 관계, 상속은 ‘is a’관계 상속과 컴포지션은 상호 배타적이지 않으며 개발자는 이 둘을 같이 사용한다. 다음 예제는 ‘is a’와 ‘has a’의 착각에는 나오게 되는 실수이다. 1. 원은 반지름 값을 갖는 하나의 점이다(a Circle is a Point with a radius.) 그래서 Circle은 Point를 상속 class Point { private double x, y; Point(double x, double y) { this.x = x; this.y = y; } double getX() { return x; } double getY() { return y; } } class Circle extends Point { private double radius; Circle(double x, double y, double radius) { super(x, y); this.radius = radius; } double getRadius() { return radius; } } 2. 원은 한 점과 반지름을 가지고 있다(a circle has a point and a radius) class Point { private double x, y; Point(double x, double y) { this.x = x; this.y = y; } //redundant code 로 인한 유지보수 어려움(코드의 재사용 실패) double getX() { return x; } double getY() { return y; } } class Circle { private Point p; private double radius; Circle(double x, double y, double radius) { p = new Point(x, y); this.radius = radius; } double getX() { return p.getX(); } double getY() { return p.getY(); } double getRadius() { return radius; } } [출처] 오라클자바커뮤니티 - http://www.oraclejavanew.kr/bbs/board.php?bo_table=LecJava&wr_id=601 오라클자바커뮤니티에서 설립한 개발자교육6년차 오엔제이프로그래밍 실무교육센터(오라클SQL,튜닝,힌트,자바프레임워크,안드로이드,아이폰,닷넷 실무개발강의) www.onjprogramming.co.kr [개강확정강좌]오라클자바커뮤니티에서 운영하는 개발자 전문교육 ,개인80%환급(www.onjprogramming.co.kr) [주말] [10/26]C#,ASP.NET마스터 [10/26]Spring3.X, MyBatis, Hibernate실무과정 [10/27]JAVA&WEB프레임워크실무과정 [평일야간] [10/29]C#,ASP.NET마스터 [10/25]Spring3.X, MyBatis, Hibernate실무과정 [10/31]JAVA&WEB프레임워크실무과정 [주간] [11/4]Spring3.X, MyBatis, Hibernate실무과정 [기타 다른 강좌는 아래 해당 카테고리를 클릭해주세요] JAVA ORACLE iPhone/Android .NET 표준웹/HTML5 채용/취업무료교육 초보자(재학생)코스

[자바상속컴포지션]Java Inheritance & Composition

상속과 컴포지션은 동전의 양면과 같이 유사하게 서로에게 관련이 있다. 
상속은 마치 양파가 여러 껍질로 이루어진 것과 같이 계층화된 객체
컴포지션은 여러 재료(객체)가 한데 뭉쳐서 만들어진 죽
컴포지션은 개체들간의 'has a' 관계, 상속은 ‘is a’관계
상속과 컴포지션은 상호 배타적이지 않으며 개발자는 이 둘을 같이 사용한다.
다음 예제는 ‘is a’와 ‘has a’의 착각에는 나오게 되는 실수이다.

1. 원은 반지름 값을 갖는 하나의 점이다(a Circle is a Point with a radius.)
   그래서 Circle은 Point를 상속

   
   
class Point {
 private double x, y;
 Point(double x, double y) {
  this.x = x;
  this.y = y;
 }
 double getX() {
  return x;
 }
 double getY() {
  return y;
 }
}
class Circle extends Point {
 private double radius;
 Circle(double x, double y, double radius) {
  super(x, y);
  this.radius = radius;
 }
 double getRadius() {
  return radius;
 }
}
 
2. 원은 한 점과 반지름을 가지고 있다(a circle has a point and a radius)
 
class Point {
 private double x, y;
 Point(double x, double y) {
  this.x = x;
  this.y = y;
 }
 //redundant code 로 인한 유지보수 어려움(코드의 재사용 실패)
 double getX() {
  return x;
 }
 double getY() {
  return y;
 }
}
 
class Circle {
 private Point p;
 private double radius;
 Circle(double x, double y, double radius) {
  p = new Point(x, y);
  this.radius = radius;
 }
 double getX() {
  return p.getX();
 }
 double getY() {
  return p.getY();
 }
 double getRadius() {
  return radius;
 }
}

오라클자바커뮤니티에서 설립한 개발자교육6년차 오엔제이프로그래밍 실무교육센터(오라클SQL,튜닝,힌트,자바프레임워크,안드로이드,아이폰,닷넷 실무개발강의)  


[기타 다른 강좌는 아래 해당 카테고리를 클릭해주세요]

2013년 9월 29일 일요일

[자바8, JDK1.8,특징새기능>JAVA8 람다식(Lambda) 닷넷에서 제공하는 람다식(닷넷에서는 이름없는 함수를 정의할 때 람다식을 쓰죠)을 JDK1.8에서는 지원한다고 하네요

[자바8, JDK1.8,특징새기능>JAVA8 람다식(Lambda)
닷넷에서 제공하는 람다식(닷넷에서는 이름없는 함수를 정의할 때 람다식을 쓰죠)을 JDK1.8에서는 지원한다고 하네요
예제를보시죠.
 
보통 AWT, SWING에서 이벤트 처리할 때 익명 클래스를 많이 이용하죠.
btn.setOnAction(new EventHandler<ActionEvent>() { 
    @Override 
    public void handle(ActionEvent event) { 
        System.out.println("Hello OnJOracleJava!"); 
    } 
});

==> 람다식을 적용하면
btn.setOnAction( 
    event -> System.out.println("Hello OnJOracleJava!") 
);


 [개강안내]오라클자바커뮤니티에서 운영하는 개발자 전문교육 ,개인80%환급(www.onjprogramming.co.kr)


오라클자바커뮤니티에서 설립한 개발자교육6년차 오엔제이프로그래밍 실무교육센터
(오라클SQL,튜닝,힌트,자바프레임워크,안드로이드,아이폰,닷넷 실무개발강의)  


2013년 8월 2일 금요일

Java Template Method 패턴 예제 , java design pattern

Java Template Method 패턴 예제   


Template Method Pattern
 

오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷 실무전문 강의) 
www.onjprogramming.co.kr

상위클래스 쪽에 템플릿이 되는 메소드가 정의되어 있고 , 그 메소드의 정의내에는 추상메소드가 사용되너 상위클래스만 보면 추상메소드가 어떤식으로 호출되는지 알수있지만 최종적으로 어떤 처리를 하는지 모른다.
 하위클래스에서 어떠한 처리를 하는지에 관계없이 큰 틀은 상위클래스가 결정한데로 처리된다. 실제로 어떤일을 하는지는 하위클래스의 구현된 내용을 봐야 한다.
 상위클래스의 템플릿 메소드에 알고리즘이 기술되어 있으므로 하위클래스에서는 알고리즘을 일일이 기술할 필요가 없다. (개개의 하위클래스에 일일이 알고리즘을 기술한다면 수정사항이 발생되면 일일이 개별 하위클래스를 수정해야 한다.)


// AbstractDisplay.java
public abstract class AbstractDisplay { 
    public abstract void open();       
    public abstract void print();       
    public abstract void close();       
    public final void display() {     
        open();                           
        for (int i = 0; i < 5; i++) {     
            print();                   
        }
        close();                           
    }
}

// GreetingDisplay.java
public class GreetingDisplay extends AbstractDisplay { 
    private String s;                               
    public GreetingDisplay(String s) {    this.s =s;              }
    public void open() {                         
        System.out.println("hello " + s);                 
    }
    public void print() {                           
        System.out.println("your name is " + s);                     
    }
    public void close() {                         
        System.out.println("bye~ " + s);               
    }
}
// StringDisplay.java
public class StringDisplay extends AbstractDisplay {   
    private String string;                             
    private int width;                                 
    public StringDisplay(String string) {             
        this.string = string;                         
        this.width = string.getBytes().length;         
    }
    public void open() {    printLine();    }
    public void print() {  System.out.println("|" + string + "|");    }
    public void close() {  printLine();      }
    private void printLine() {                   
        System.out.print("+");                   
        for (int i = 0; i < width; i++) {  System.out.print("-");      }
        System.out.println("+");               
    }
}
// Main.java
public class Main {
    public static void main(String[] args) {
        AbstractDisplay d1 = new GreetingDisplay("이종철");                 
        AbstractDisplay d2 = new StringDisplay("Hello, world.");   
        AbstractDisplay d3 = new StringDisplay("안녕하세요~");   
        d1.display();                                               
        d2.display();                                               
        d3.display();                                               
    }
}  

java inheritence and composition(자바 상속 컴포지션)

상속과 컴포지션은 동전의 양면과 같이 유사하게 서로에게 관련이 있다. 
 - 상속은 마치 양파가 여러 껍질로 이루어진 것과 같이 계층화된 객체
 - 컴포지션은 여러 재료(객체)가 한데 뭉쳐서 만들어진 죽
 - 컴포지션은 개체들간의 'has a' 관계, 상속은 ‘is a’관계
 - 상속과 컴포지션은 상호 배타적이지 않으며 개발자는 이 둘을 같이 사용한다.

오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷 실무전문 강의) 



Composition Exam

class Soap {
  private String s;
  Soap() {
    System.out.println("Soap()");
    s = new String("Constructed");
  }
  public String toString() { return s; }
}

public class Bath {
  private String 
    // Initializing at point of definition:
    s1 = new String("Happy"), 
    s2 = "Happy", 
    s3, s4;
  Soap castille;
  int i;
  float toy;
  Bath() {
    System.out.println("Inside Bath()");
    s3 = new String("Joy");
    i = 47;
    toy = 3.14f;
    castille = new Soap();
  }
  void print() {
    // Delayed initialization:
    if(s4 == null)
      s4 = new String("Joy");
    System.out.println("s1 = " + s1);
    System.out.println("s2 = " + s2);
    System.out.println("s3 = " + s3);
    System.out.println("s4 = " + s4);
    System.out.println("i = " + i);
    System.out.println("toy = " + toy);
    System.out.println("castille = " + castille);
  }

  public static void main(String[] args) {
    Bath b = new Bath();
    b.print();
  }
}