2011년7월28일_JAVA class_상속-클래스 멤버(속성, 메소드)들을 자식클래스에게 물려주어 공통된 부분을 제외한 나머지만 추가하여 코드의 재활용을 쉽게 하자.



JAVA에 많은 시간을 투자하기 시러~
그러나 상속이라는 개념은 매우 중요한 것 같다.
//그 부분만 정리해둘것.




image 

상속: 기존 클래스를 확장해서 새로운 클래스를 만드는 기술. 부모클래스의 구성요소를 자식클래스에게 조건부 물려준다.
       private접근제어지시어로 선언되어 있는 멤버들은 상속되지 않고,
       protected지시어는 자식클래스에게 물려주나 외부 클래스에서 접근할 수 없다.
       ex) 좋은 클래스 구입 –> 상속 –> 커스터마이징 –> 새로운 내게 맞는 좋은 클래스


image 

private 즉, 아무리 부모와 자식간이라도 개인의 사생활이 있다.
그 사생활은 보호되어야 한다.


참조(Reference)




DSCN3805 DSCN3806 DSCN3807



● ExtendsTest.java

   1: //20110728
   2: //현대자동차에서 의뢰가 들어와 프로그램작성.
   3: //빨간색차를 시속 60km로 달리게 해주세요.
   4: //다음엔,
   5: //슈퍼카를 만들어주세요.
   6: //슈퍼카는 터보엔진이 있음 (슈퍼엔진)
   7: //예전에 만든 Car클래스와 공통된 부분이 있으니 재활용해보자.
   8: //상속~
   9: package kr.ac.busanit;
  10:  
  11: class Car {
  12:     //멤버변수
  13:     protected int        speed;
  14:     protected String    color;
  15:     
  16:     //생성자
  17:     Car() {
  18:         
  19:     }
  20:     
  21:     //getter/setter
  22:     public int getSpeed() {
  23:         return speed;
  24:     }
  25:  
  26:     public void setSpeed(int speed) {
  27:         this.speed = speed;
  28:     }
  29:  
  30:     public String getColor() {
  31:         return color;
  32:     }
  33:  
  34:     public void setColor(String color) {
  35:         this.color = color;
  36:     }
  37:     
  38:     //멤버메소드
  39:     public void run() {
  40:         System.out.println("달리다.");
  41:     }
  42: }
  43:  
  44: class SuperCar extends Car {
  45:     //썬루프도 추가, ABS도 추가
  46:     private String sunroof;
  47:     private String ABS;
  48:     private String OOS;
  49:         
  50:     //기존 Car클래스 멤버를 그대로 가지고 있고 터보엔진만 추가됨.
  51:     public void toborEngineRun() {
  52:         this.speed += 100;
  53:     }
  54: }
  55:  
  56: class SuperSuperCar extends SuperCar {
  57:     
  58: }
  59:  
  60: public class ExtendsTest {
  61:  
  62:     /**
  63:      * @param args
  64:      */
  65:     public static void main(String[] args) {
  66:         // TODO Auto-generated method stub
  67:         Car sonata1 = new Car();
  68:         sonata1.setColor("빨간색");
  69:         sonata1.setSpeed(60);
  70:         System.out.println("차의 색상은 " + sonata1.getColor());
  71:         System.out.println("차의 속도는 " + sonata1.getSpeed());
  72:         sonata1.run();
  73:  
  74:         SuperCar sonata2 = new SuperCar();
  75:         sonata2.setColor("빨간색");
  76:         sonata2.setSpeed(60);
  77:         sonata2.toborEngineRun();
  78:         System.out.println("차의 색상은 " + sonata2.getColor());
  79:         System.out.println("차의 속도는 " + sonata2.getSpeed());
  80:         sonata2.run();
  81:  
  82:     }
  83:  
  84: }


<실행결과>

image



● InheritanceExample1.java (아래의 두 파일이 필요)

   1: package kr.ac.busanit;
   2:  
   3: public class InheritanceExample1 {
   4:  
   5:     /**
   6:      * @param args
   7:      */
   8:     public static void main(String[] args) {
   9:         // TODO Auto-generated method stub
  10:         CheckingAccount obj = new CheckingAccount();
  11:         obj.setAccountNo("111-22-33333333");    
  12:         obj.setOwnerName("홍길동");           
  13:         obj.setCardNo("5555-6666-7777-8888");      
  14:         obj.deposit(100000);     
  15:         try {
  16:             int paidAmount = obj.pay("5555-6666-7777-8888", 47000);     
  17:             System.out.println("지불액:" + paidAmount);
  18:             System.out.println("잔액:" + obj.getBalance());
  19:         }
  20:         catch (Exception e) {   
  21:             String msg = e.getMessage();
  22:             System.out.println(msg);
  23:         }
  24:  
  25:     }
  26:  
  27: }


● Account.java

   1: package kr.ac.busanit;
   2:  
   3: public class Account {
   4:     //멤버변수
   5:     private String accountNo;
   6:     private String ownerName;
   7:     private int balance;
   8:         
   9:     public String getAccountNo() {
  10:         return accountNo;
  11:     }
  12:  
  13:     public void setAccountNo(String accountNo) {
  14:         this.accountNo = accountNo;
  15:     }
  16:  
  17:     public String getOwnerName() {
  18:         return ownerName;
  19:     }
  20:  
  21:     public void setOwnerName(String ownerName) {
  22:         this.ownerName = ownerName;
  23:     }
  24:  
  25:     public int getBalance() {
  26:         return balance;
  27:     }
  28:  
  29:     public void setBalance(int balance) {
  30:         this.balance = balance;
  31:     }
  32:  
  33:     //멤버메소드
  34:     public void deposit(int amount) {
  35:         balance += amount;
  36:     }
  37:     
  38:     public int withdraw(int amount) throws Exception {
  39:         if (balance < amount)
  40:             throw new Exception("잔액이 부족합니다.");
  41:         balance -= amount;
  42:         return amount;
  43:     }
  44: }


● CheckingAccount.java

   1: package kr.ac.busanit;
   2:  
   3: public class CheckingAccount extends Account {
   4:     private String cardNo;
   5:         
   6:     public String getCardNo() {
   7:         return cardNo;
   8:     }
   9:     
  10:     public void setCardNo(String cardNo) {
  11:         this.cardNo = cardNo;
  12:     }
  13:  
  14:     int pay(String cardNo, int amount) throws Exception {  
  15:         if (!cardNo.equals(this.cardNo) || (this.getBalance() < amount))
  16:             throw new Exception("지불이 불가능합니다.");
  17:         return withdraw(amount);
  18:     }
  19:  
  20: }


<실행결과>

image