'C/Java'에 해당되는 글 59건

  1. 2007.11.06 인터페이스의 다형성 by 청웨일
  2. 2007.11.06 추상클래스 by 청웨일
  3. 2007.11.06 객체를 배열로 다루기 by 청웨일
  4. 2007.11.06 참조변수와 인스턴스의 연결 by 청웨일
  5. 2007.11.06 접근제어자 by 청웨일

인터페이스의 다형성

C/Java : 2007. 11. 6. 14:23

- 개발시간의 단축

- 표준화 가능

- 관계없는 클래스간에 관계설정 가능

- 독립적인 프로그래밍 가능



1)

interface Parseable {                                            //구문 분석 작업 수행
 public abstract void parse(String fileName);
}

class ParserManager {                                         //리턴타입 : Parseable인터페이스
 public static Parseable getParser(String type) {
  if(type.equals("XML")) {
   return new XMLParser();                                  
  }
  else {
   Parseable p = new HTMLParser();
   return p;
  }
 }
}
class XMLParser implements Parseable {
 public void parse(String fileName) {

             //구문 분석 작업 수행 코드
  System.out.println(fileName + " - XML parsing completed.");
 }
}

class HTMLParser implements Parseable {
 public void parse(String fileName) {

             //구문 분석 작업 수행 코드
  System.out.println(fileName + " - HTML Parsing completed.");
 }
}

public class ParserTest {
 public static void main(String args[]) {
  Parseable parser = ParserManager.getParser("XML");
  parser.parse("document.xml");
  parser = ParserManager.getParser("HTML");
  parser.parse("document2.html");
 }
}



2)

public class RepairableTest {
 public static void main(String[] args) {
  Tank t = new Tank();
  DropShip d = new DropShip();
  Marine m = new Marine();
  SCV s = new SCV();
 
  s.repair(t);
  s.repair(d);

   //marine으로는 인터페이스를 구현하지 않았기 때문에 repair메서드를 부를수 없다.
 }
}


class Unit {
 int hitPoint;
 final int MAX_HP;
 
 Unit(int hp) {
  MAX_HP = hp;
 }
}


interface Repairable { }


class GroundUnit extends Unit {
 GroundUnit(int hp) {
  super(hp);
 }
}


class AirUnit extends Unit {
 AirUnit(int hp) {
  super(hp);
 }
}


class Tank extends GroundUnit implements Repairable {
 Tank() {
  super(150);
  hitPoint = MAX_HP;
 }
 public String toString() {
  return "Tank";
 }
}


class DropShip extends AirUnit implements Repairable {
 DropShip() {
  super(125);
  hitPoint = MAX_HP;
 }
 
 public String toString() {
  return "DropShip";
 }
}


class Marine extends GroundUnit {
 Marine() {
  super(40);
  hitPoint = MAX_HP;
 }
}


class SCV extends GroundUnit implements Repairable{
 SCV() {
  super(60);
  hitPoint = MAX_HP;
 }
 void repair(Repairable r) {       
//marine은 Repairable을 상속하지 않기 때문에 매개변수로 들어올수 없다
  if(r instanceof Unit) {
   Unit u = (Unit)r;          //형변환이 가능하면 형변환 한다.
   while(u.hitPoint == u.MAX_HP) {    //hitPoint가 MAX_HP와 같을 때까지 증가시킨다.
    u.hitPoint++;
   }
   System.out.println(u.toString() + "의 수리가 끝났습니다.");
  }
 }
}




마린은 SCV로 수리되는 유닛이 아니기 때문에 repair메서드를 사용하자고 하기엔 무리가 있다.

마린은 메딕이 필요하다.


때문에 같은 Ground유닛이지만 치료개념인 마린을 수리개념인 탱크, SCV와 분리시키고

수리가 가능한 Air유닛 드랍쉽에도 repair를 적용시키기 위해 인터페이스로 상속하여

각기 다른 클래스를 상속하는 클래스에 인터페이스로 상속관계를 주었다.

Posted by 청웨일

추상클래스

C/Java : 2007. 11. 6. 14:22

- 추상클래스는 미완성이다.

- 미완성 메서드를 포함하고 있다.

- abstract : 추상메서드가 있으니 상속을 통해 구현해야 한다는 의미

- 추상메서드 : 선언부로만 이루어진 메서드, 상속을 통해 자식클래스에서 구현부 정의.


 인터페이스


- 추상화의 정도가 높다.

- 추상메서드만을 구성으로 한다.

- 다른클래스를 작성하는데 도음을 주기위해 작성된다.


- 모든 멤버변수를 public static final로 선안하며 생략가능

- 모든 메서드는 public abstract로 선언하며 생략가능


- 클래스가 아닌 인터페이스로부터만 상속가능

- 여러개의 인터페이스로부터 다중상속 가능




public class FighterTest {
 public static void main(String[] args) {
  Fighter f = new Fighter();
  if(f instanceof Unit) {
   System.out.println("f는 Unit클래스의 자손입니다.");
  }
  if(f instanceof Fightable) {
   System.out.println("f는 Fightable인터페이스를 구현했습니다.");
  }
  if(f instanceof Movable) {
   System.out.println("f는 Movable인터페이스를 구현했습니다.");
  }
  if(f instanceof Attackable) {
   System.out.println("f는 Attackable인터페이스를 구현했습니다.");
  }
  if(f instanceof Object) {
   System.out.println("f는 Object클래스의 자손입니다.");
  }
 }
}


class Fighter extends Unit implements Fightable {
 public void move(int x, int y) { }
 public void attack(Unit u) { }
}


class Unit {
 int currentHP;
 int x;
 int y;
}


interface Fightable extends Movable, Attackable { }
interface Movable { void move(int x, int y); }
interface Attackable { void attack(Unit u); }

Posted by 청웨일

객체를 배열로 다루기

C/Java : 2007. 11. 6. 11:48

- 조상타입의 참조변수로 자손타입의 객체를 참조하는 것이 가능하다.

- 조상타입의 참조변수를 배열로 선언하여 각각 자손타입의 객체를 저장한다.


Vactor클래스


- 내부적으로 Object타입의 배열을 가지고 있다.

- 배열의 객체를 추가/제거할수 있게 작성되어 있다.

- 동적 배열이기 때문에 저장할 객체의 개수에 신경쓰지 않아도 된다.


* Vector() - 생성자

* boolean add(Object o) - 객체추가, 성공하면 true 실패하면 false 반환

* boolean remove(Object o) - 저장된 객체를 제거, 성공하면 true 실패하면 false 반환

* boolean isEmpty() - Vector가 비어있는지 검사, 비어있으면 true 아니면 false 반환

* Object get(int index) - 지정된 위치의 객체를 반환한다. 형변환 필요.

* int size() - Vector에 저장된 객체의 개수 반환


Posted by 청웨일

멤버변수가 조상클래스와 자손클래스의 중복으로 정의된 경우

조상타입의 참조변수를 사용했을 때는 조상클래스에 선언된 멤버변수가 사용되고,

자손타입의 참조변수를 사용했을 때는 자손클래스에 선언된 멤버변수가 사용된다.


중복정의 되지 않았을 경우, 각 타입의 참조변수를 사용했을 때의 차이는 없다.
 


자손클래스에 선언된 멤버변수와 조상클래스로부터 상속받은 멤버변수를 구분하는데 super와 this를 쓴다.


Posted by 청웨일

접근제어자

C/Java : 2007. 11. 6. 11:23

- 클래스의 내부에 선언된 데이터를 보호하기 위함.(캡슐화)

- 사용처 : 클래스 - public, default / final, abstract

               멤버변수 - public, protected, default, private / final, abstract, static

               메서드 - public, protected, default, private / final, static

               생성자

               지역변수 - final


public / 접근제한이 전혀 없다

protected / 다른패키지의 자손클래스까지 접근 가능

default / 같은 패키지 안에서만 접근 가능

private / 같은 클래스 안에서만 접근 가능


 제어자

 같은클래스

 같은패키지

 자손클래스

 전체

 public

 ○

 ○

 ○

 ○

 protected

 ○

 ○

 ○


 default

 ○

 ○



 private

 ○





* default - 아무 접근제어자도 사용하지 않는 것.


캡슐화 - (접근제어자를 이용해 제한)


생성자의 접근제어자를

private로 지정하면 외부에서 접근할수 없어 객체를 생성할 수 없게 된다.

클래스 내부에서는 생성가능.

객체를 생성해서 반환해줄 public메서드로 외부에서 클래스를 이용  -> public static이어야 한다.

생성자가 private인 클래스는 다른 클래스의 조상이 될수 없다.(final추가)


- 메서드에 static는 몸통이 있는 메서드에만 사용할 수 있기 때문에 abstract(추상)를 함께 쓸수 없다.

- final은 클래스를 확장할수 없다는 의미이고, abstract는 상속으로 완성되어야 한다의 의미로 동반불가

- abstract메서드의 접근제어자는 private일수 없다.

- private는 메서드를 오버라이딩 할수 없기 때문에 꼭 final과 함께 쓸 필요는 없다.

Posted by 청웨일