'C'에 해당되는 글 116건

  1. 2007.11.06 예외처리(Try~) by 청웨일
  2. 2007.11.06 CarTest by 청웨일
  3. 2007.11.06 자바의 제귀 by 청웨일
  4. 2007.11.06 인터페이스 by 청웨일
  5. 2007.11.06 인터페이스의 다형성 by 청웨일

예외처리(Try~)

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

- 에러로 인해 프로그램이 비정상 종료되지 않도록 처리한다.


Eexception : 에러 상태, 메소드의 기대되지 않은 결과가 발생

Throwing an Exception : 예외적인 상태를 발견하고 예외를 발생시킨다.

Catching an Exception : 예외가 발생했을때 예외 핸들러에 의해 catch할수 있다.

Handling an Exception : 예외 처리


1) try 블록 - 예외가 발생할수 있는 문장을 try키워드로 둘러싼 구조.

2) catch 블록 - 발생한 예외는 catch 블록 내로 걸려든다.

                  - try블록은 0개 이상의 catch블록이 뒤따른다.(없으면 finally블록)

3)finally 블록 - catch블록 뒤에, 없으면 try블록 뒤에 온다.


*

try {

//예외가 발생할수 있는 문장들

}

catch(...) {

//try블록에서 발생할수 있는 예외 처리

}

finally {

//해제 작업

}

Posted by 청웨일

CarTest

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

//CarTest.java


public class CarTest {
 static final int COUPE = 1;
 static final int CONVERTIBLE = 2;
 static final int T_TOP = 3;
 
 static final int V4 = 1;
 static final int V6 = 2;
 static final int V8 = 3;
 static final int V10 = 4;
 
 static int engineType;
 static int bodyType;
 static int topSpeed;
 static int gas;
 static int oil;
 static boolean isRunning;
 static int currentSpeed;
 
 public static void turnOn() {
  isRunning = true;
 }
 
 public static void turnOff() {
  isRunning = false;
 }
 
 public static void accelerate() {
  switch(engineType) {
  case V4:
   speedUp(2);
   break;
  case V6:
   speedUp(3);
   break;
  case V8:
   speedUp(4);
   break;
  case V10:
   speedUp(5);
   break;
  }
 }
 
 public static void speedUp(int amount) {
  if(isRunning == false) {     //자동차가 멈춰있으면 아무것도 하지 않고 리턴
   return;
  }
 
  if((currentSpeed + amount) >= topSpeed) {
   currentSpeed = topSpeed;
  }
 
  else {
   currentSpeed += amount;
  }
 }
 
 public static void decelerate() {
  if(isRunning == false) {      //자동차가 멈춰있으면 아무것도 하지 않고 리턴
   return;
  }
  if((currentSpeed - 5) <= 0) {
   currentSpeed = 0;
  }
  else {
   currentSpeed -= 5;
  }
 }
 
 public static void main(String[] args) {
  engineType = V10;
  bodyType = CONVERTIBLE;
  topSpeed = 185;
  isRunning = false;
  currentSpeed = 0;     //자동차의 속성
 
  turnOn();    //자동차를 출발시킨다.
  for(int i=0; i<10; i++) {
   accelerate();
   System.out.println("Current Speed a: " + currentSpeed);
  }
  for(int i=0; i<5; i++) {
   decelerate();
   System.out.println("Current Speed d: " + currentSpeed);
  }
  turnOff();
 }
}



======================================================

 

여러대의 자동차를 표현하고자 할때

자동차의 속성을 따로 클래스로 빼내 정의할수 있다.


//Car.java


public class Car {
 static final int COUPE = 1;
 static final int CONVERTIBLE = 2;
 static final int T_TOP = 3;
 
 static final int V4 = 1;
 static final int V6 = 2;
 static final int V8 = 3;
 static final int V10 = 4;
 
 static int engineType;
 static int bodyType;
 static int topSpeed;
 static int gas;
 static int oil;
 static boolean isRunning;
 static int currentSpeed;
}


//CarTest2.java


public class CarTest2 {


 public static void turnOn(Car c) {
  c.isRunning = true;
 }
 
 public static void turnOff(Car c) {
  c.isRunning = false;
 }
 
 public static void accelerate(Car c) {
  switch(c.engineType) {
  case Car.V4:
   speedUp(c, 2);
   break;
  case Car.V6:
   speedUp(c, 3);
   break;
  case Car.V8:
   speedUp(c, 4);
   break;
  case Car.V10:
   speedUp(c, 5);
   break;
  }
 }
 
 public static void speedUp(Car c, int amount) {
  if(c.isRunning == false) {
   return;
  }
 
  if((c.currentSpeed + amount) >= c.topSpeed) {
   c.currentSpeed = c.topSpeed;
  }
 
  else {
   c.currentSpeed += amount;
  }
 }
 
 public static void decelerate(Car c) {
  if(c.isRunning == false) {
   return;
  }
  if((c.currentSpeed - 5) <= 0) {
   c.currentSpeed = 0;
  }
  else {
   c.currentSpeed -= 5;
  }
 }
 
 public static void main(String[] args) {
  Car c1 = new Car();           //자동차의 속성을 정의한다. 객체를 생성한다.
  c1.engineType = Car.V10;
  c1.bodyType = Car.CONVERTIBLE;
  c1.topSpeed = 185;
  c1.isRunning = false;
  c1.currentSpeed = 0;
 
  turnOn(c1);
  for(int i=0; i<10; i++) {
   accelerate(c1);
   System.out.println("Current Speed a: " + c1.currentSpeed);
  }
  for(int i=0; i<5; i++) {
   decelerate(c1);
   System.out.println("Current Speed d: " + c1.currentSpeed);
  }
  turnOff(c1);
 }
}


Posted by 청웨일

자바의 제귀

C/Java : 2007. 11. 6. 14:24
public class FactorialRecursive {
 public static int factorial(int n) {
  if(n == 1) return 1;            //n이 1이 되면 1을 반환한다.
  return n*factorial(n-1);     //아니면 (n-1)로 재귀
 }
 
 public static void main(String[] args) {
  System.out.println("5 factorial = " + factorial(5));
 }
}
Posted by 청웨일

인터페이스

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

인터페이스 정의


 [public] interface iname [extends i2name]

- public을 포함할수 있지만 생략

- abstract를 포함할수 있지만 생략

- 필드에 static과 final을 포함할수 있지만 생략

- 모든 인터페이스는 public과 abstract이다.

- 정의할수 있는 인터페이스의 속성은 static과 final


인터페이스 키워드 implements


[public] [qualefiers] class classname implements iname ( , i2name, ...)

- 클래스는 여러개의 인터페이스를 구현할 수 있다.

- 클래스는 avstract 또는 final일 수 있다.

- 클래스는 한개의 클래스 확장과 여러 개의 인터페이스를 구현할수 있다.


인터페이스와 추상 클래스

- 해당 기능이 객체에 매우 잘 결합되어 있을때는 추상 메서드

- 해당 기능이 객체에 보조적인 경우 인터페이스

- 해당 기능이 다른 객체에 광범위하게 적용가능하면 인터페이스




매개변수를 통해 동적으로 제공


class A {
 void autoPlay(I i) {
  i.play();
 }
}

interface I {
 public abstract void play();
}

class B implements I {
 public void play() {
  System.out.println("play in B class");
 }
}

class C implements I {
 public void play() {
  System.out.println("play in C class");
 }
}

public class InterfaceTest {
 public static void main(String[] args) {
  A a = new A();
  a.autoPlay(new B());
  a.autoPlay(new C());
 }
}



제 3의 클래스를 통해 제공


public class InterfaceTest {
 public static void main(String[] args) {
  A a = new A();
  a.methodA();
 }
}

class A {
 void methodA() {
  I i = InstanceManager.getInstance();  //제 3의 클래스 메서드를 통해 인터페이스 I를
  i.methodB();                                   // 구현한 클래스의 인스턴스를 얻어온다.
 }
}

interface I {
 public abstract void methodB();
}

class B implements I {
 public void methodB() {
  System.out.println("methodB in B class");
 }
}

class InstanceManager {
 public static I getInstance() {
  return new B();
 }
}

Posted 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 청웨일