본문 바로가기

JAVA

상속(inheritance)

상속이란 기존클래스를 확장해서 새로운 클래스를 만드는 기술

언제 상속이 필요한가?
 - 기존 클래스와 유사한 클래스를 만들어야 할 경우

상속 전 소스
package kr.ac.busanit;

class Car {
  //멤버변수
  protected int speed;
  protected String color;    //private는 복사가 안된다.
  
  //생성자
  public Car() {
    
  }
  
  //멤버메소드
  public void run() {
    System.out.println("달리다.");
  }
  
  public int getSpeed() {
    return speed;
  }

  public void setSpeed(int speed) {
    this.speed = speed;
  }

  public String getColor() {
    return color;
  }

  public void setColor(String color) {
    this.color = color;
  }
}


public class ExtendsTest {
  
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    Car sonata1 = new Car();
    
    sonata1.setSpeed(60);
    sonata1.setColor("빨간색");
        
    System.out.println("차의 색상은 : " + sonata1.getColor());
    System.out.println("차의 속도는 : " + sonata1.getSpeed());
  }

}

[결과]
차의 색상은 : 빨간색
차의 속도는 : 60



상속 후 소스
package kr.ac.busanit;

class Car {
  //멤버변수
  protected int speed;
  protected String color;    //private는 복사가 안된다.
  
  //생성자
  public Car() {
    
  }
  
  //멤버메소드
  public void run() {
    System.out.println("달리다.");
  }
  
  public int getSpeed() {
    return speed;
  }

  public void setSpeed(int speed) {
    this.speed = speed;
  }

  public String getColor() {
    return color;
  }

  public void setColor(String color) {
    this.color = color;
  }
}

class SuperCar extends Car{
//extends는 상속, Car안에 클래스들을  복사하지 않아도 스스로 복사한다.
  
  private String sunroof;
  private String ABS;
  private String QOS;
  
  public void toborEngineRun(){
    this.speed += 100;
  }
}
public
 class ExtendsTest {
  
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    SuperCar sonata1 = new SuperCar();
    
    sonata1.setSpeed(60);
    sonata1.setColor("빨간색");
    sonata1.toborEngineRun();
    
    System.out.println("차의 색상은 : " + sonata1.getColor());
    System.out.println("차의 속도는 : " + sonata1.getSpeed());
  }

}


[결과]
차의 색상은 : 빨간색
차의 속도는 : 160





Account.java

package kr.ac.busanit;

public class Account {
  
    String accountNo;    //계좌번호
    String ownerName;    //예금주
    int balance;         //잔액
    
    void deposit(int amount) {
        balance += amount;
    }
    int withdraw(int amount) throws Exception {
        if (balance < amount)
            throw new Exception("잔액이 부족합니다.");
        balance -= amount;
        return amount;
    }

}



CheckingAccount.java

package kr.ac.busanit;

public class CheckingAccount extends Account {
  
//extends(상속) Account(상속할 클래스 이름)
  String cardNo;  //직불카드 번호에해당하는 필드
                                        
  int pay(String cardNo, int amount) throws Exception {  
    if (!cardNo.equals(this.cardNo) || (balance < amount))
      throw new Exception("지불이 불가능합니다.");
    return withdraw(amount);
  }

}

직불카드넘버가 다르거나 잔액이 인출금액보다 작은 경우에는 if문을 수행하게 되있다.


InheritanceExample1.java
package kr.ac.busanit;

public class InheritanceExample1 {

  public static void main(String[] args) {
    
    CheckingAccount obj = new CheckingAccount();
        obj.accountNo = "111-22-33333333";    
        obj.ownerName = "홍길동";           
        obj.cardNo = "5555-6666-7777-8888";      
        obj.deposit(100000);     
        try {
            int paidAmount = obj.pay("5555-6666-7777-8888"55000);     
            System.out.println("지불액:" + paidAmount);
            System.out.println("잔액:" + obj.balance); //잔고가 얼마?
        }
        catch (Exception e) {   
            String msg = e.getMessage();
            System.out.println(msg);
        }
  }
}

'JAVA' 카테고리의 다른 글

QUIZ  (0) 2011.08.17
객체와 클래스(2)  (0) 2011.07.25
캡슐화란?  (0) 2011.07.22
C와 JAVA 구조체 비교  (0) 2011.07.22
객체와 클래스(1)  (0) 2011.07.21