Presentation is loading. Please wait.

Presentation is loading. Please wait.

10장 객체-지향 프로그래밍 II.

Similar presentations


Presentation on theme: "10장 객체-지향 프로그래밍 II."— Presentation transcript:

1 10장 객체-지향 프로그래밍 II

2 상속

3 왜 상속을 하는가? ? 프로그램 설계 클래스 계층 구조 설계

4 상속이란 무엇인가? 상속 용어 is-a 관계를 모델링하는 데 사용 기존 클래스에 새로운 변수 및 메소드들을 추가
새로운 클래스 정의 혹은 유도 용어 슈퍼 클래스 = 베이스 클래스 = 부모 클래스 서브 클래스 = 파생 클래스 = 자식 클래스 is-a 관계를 모델링하는 데 사용 “Car is a vehicle."에서 Car과 Vehicle과의 관계 is – a 관계가 성립하는 경우에 상속 가능 서브 클래스는 슈퍼 클래스의 서브타입 (subtype)

5 상속 관계 도식화 Vehicle Car 상속 관계 도식화
The child is-a more specific version of the parent An object of a child class can appear whenever an object of a parent class is expected Vehicle Car

6 서브클래스 정의 Java에서 상속 상속을 위해서 extends라는 키워드를 사용
class Car extends Vehicle { // class contents } 단일 상속(single inheritance)만을 지원 하나의 슈퍼클래스로부터 상속 받음

7 예: Book and Dictionary class Book { protected int pages;
// Sets up a book with the specified number of pages. public Book (int num_pages) { pages = num_pages; } // constructor Book // Prints a message using the value of an instance variable. public void page_message () { System.out.println ("Number of pages: " + pages); } // method page_message } // class Book

8 예: Book and Dictionary class Dictionary extends Book {
private int definitions; public Dictionary (int num_pages, int num_definitions) { super (num_pages); definitions = num_definitions; } // constructor Dictionary public void definition_message () { System.out.println ("Number of definitions: " + definitions); System.out.println ("Definitions per page: " + definitions/pages); } // method definition_message } // class Dictionary

9 상속과 가시성 조정자 protected는 왜 필요한가 ? C++의 protected Java의 protected
나와 내 자식들만을 위한 것 public으로 한다면 어떻게 될까? private으로 한다면 어떻게 될까? C++의 protected protected 멤버는 자식에 상속된다. 자식 클래스에서 접근/사용 가능 Java의 protected Protected 멤버는 자식에 상속된다. 같은 패키지 내에서 접근/사용 가능

10 상속과 가시성 조정자 상속 시 가시성 부모클래스 public protected private 자식클래스 inaccesible

11 메쏘드 재정의

12 메쏘드 재정의(Method Overriding)
클래스의 상속관계에서 발생한다. 부모 클래스로부터 상속된 메소드를 자식 클래스에서 다른 일을 하도록 같은 이름으로 재정의 유의할 점 재정의된 메쏘드는 부모 클래스의 메쏘드와 시그너처가 같아야 함 final으로 선언한 메소드는 재정의 불가 객체 타입에 따라 호출될 메쏘드가 결정된다.

13 메쏘드 재정의: 예 class Fruit { int grams; int cals_per_gram;
int total_calories( ) { /* … */ } void peel( ) { System.out.print(“peel a Fruit”); } } class Lemon extends Fruit { void squeeze( ) { /* … */ } // Fruit 클래스의 peel() 메쏘드를 Lemon 클래스가 재정의 void peel( ) { super.peel(); System.out.println(“, which is a lemon”);

14 메쏘드 재정의: 예 class Example { public static void main(String args[]) {
Fruit fruit = new Fruit(); Lemon lemon = new Lemon(); fruit.peel(); lemon.peel(); fruit = lemon; }

15 super 참조 super는 슈퍼클래스를 지칭하는 참조 super() 슈퍼클래스의 멤버 필드나 메소드를 지칭할 때 사용
super.field super.method() super() super()는 슈퍼클래스의 생성자를 호출 super()는 생성자의 맨 처음 부분에 위치 서브클래스 생성자에서 슈퍼클래스의 생성자를 호출

16 참조와 상속 Fruit Lemon 객체 참조 변수는 선언된 클래스 혹은 그 하위 클래스들의 객체를 참조할 수 있다. 예
Fruit fruit; fruit = new Lemon(); Fruit Lemon

17 다형 참조 다형 참조(Polymorphic reference) 예 if (x >0 ) fruit = lemon;
여러 클래스의 객체를 참조 여러 메쏘드 호출 if (x >0 ) fruit = lemon; fruit.peel(); fruit가 Fruit 객체를 참조하는 경우 fruit가 Lemon 객체를 참조하는 경우

18 메쏘드 호출 호출될 메쏘드 결정 ? 주의 변수가 선언된 타입이 아니고 참조된 객체의 타입에 따라 결정된다.
호출될 메쏘드 결정 ? 변수가 선언된 타입이 아니고 참조된 객체의 타입에 따라 결정된다. 따라서 실행-시간에 결정된다 This is a dynamic binding ! 주의 한 줄의 코드가 경우에 따라 다른 메쏘드를 호출할 수 있다.

19 중복정의와 재정의 중복정의(overloading)와 재정의(overriding) 혼동하지 말자! 중복정의 재정의
중복정의와 재정의 중복정의(overloading)와 재정의(overriding) 혼동하지 말자! 중복정의 한 클래스 내에서 여러 메쏘드 정의 같은 이름이지만 시그너처는 다름. 재정의 부모로부터 상속된 메쏘드를 다시 정의 시그너처가 같아야 함. 시그너처가 다르다면 어떻게 될까?

20 클래스 설계

21 클래스 설계는 어떻게 ? 좋은 클래스 설계는 어떤 것일까 ? 클래스 계층구조는 변화에 따라 확장 혹은 수정된다.
가능하면 공통적인 것들은 상부에 위치하는 것이 좋다. 왜 ? 클래스 계층구조는 변화에 따라 확장 혹은 수정된다. 모든 상황에 맞는 좋은 클래스 계층구조는 없다.

22 클래스 계층구조 클래스 상속에 따른 계층구조 Business RetailBusiness ServiceBusiness KMart
Macys EMart

23 Object 클래스 Object class Object 클래스가 포함한 유용한 메쏘드 클래스 계층구조에서 꼭대기에 있다.
toString()

24 추상 클래스

25 추상 클래스(Abstract Class)
아직 덜 구현된 클래스 추상 메쏘드(abstract method) 메쏘드 의 인터페이스만 정의되어 있는 메쏘드 메쏘드 의 선언 시 abstract라는 키워드 사용 visibilty_type abstract return_type function_name(argumet_list) ; 추상 메소드는 몸체를 가지지 않는다. 추상 클래스 추상 메소드를 갖는 클래스는 추상 클래스이다. 추상 클래스를 상속 받는 서브 클래스가 추상 메소드를 구현

26 추상 클래스 클래스 계층구조에서 사용 추상 클래스로부터 객체 생성 불가 ! 공통적인 것들을 적절한 위치에 배치하는데 유용
추상 클래스의 자식 클래스가 추상 메소드 구현 자식이 구현하지 않으면 자식 클래스도 추상 클래스 추상 클래스로부터 객체 생성 불가 !

27 예제 예제 : Shape.java 예제 : Circle.java 파일 1 public abstract class Shape {
public abstract double area(); public abstract double circumference(); 4 } 예제 : Circle.java 파일 1 class Circle extends Shape{ protected int r; 3 public Circle() { r = 0; } 7 11 public double circumference() { return Math.PI*2*r; } 15 public double area() { return Math.PI*r*r; } ……….

28 예제 예제 : ShapeUser.java 결과 1 class ShapeUser { 2
public static void main(String arg[]) { Shape shape[] = new Shape[3]; 5 shape[0] = new Circle(5); shape[1] = new Circle(7); shape[2] = new Rectangle(9, 5); 9 System.out.println("shape[0]'s area = " + shape[0].area()); System.out.println("shape[1]'s area = " + shape[1].area()); System.out.println("shape[2]'s area = " + shape[2].area()); …………... 결과 % java ShapeUser shape[0]'s area = shape[1]'s area = shape[2]'s area = 45.0

29 인터페이스

30 인터페이스(interface) 설계할 클래스들에 대한 명세(specification) 인터페이스
추상 메쏘드와 상수만으로 구성된다. abstract 키워드는 필요 없다.

31 추상 클래스와 인터페이스 차이점 상속 관련 차이점 추상 클래스는 일부 메소드는 구현 인터페이스는 전혀 구현되어 있지 않음
추상 클래스를 이용하는 경우에는 단일 상속만 지원 인터페이스는 다중 상속 (multiple inheritance) 가능

32 interface is a reserved word
None of the methods in an interface are given a definition (body) public interface Doable { public void doThis(); public int doThat(); public void doThis2 (float value, char ch); public boolean doTheOther (int num); } A semicolon immediately follows each method header

33 인터페이스 인터페이스를 구현한 클래스 implements 인터페이스 내의 메쏘드 인터페이스로부터 객체 생성 불가 !
모든 추상 메쏘드를 구현해야 한다. implements class class-name implements interface-name { } 인터페이스 내의 메쏘드 모두 public and abstract 인터페이스로부터 객체 생성 불가 !

34 인터페이스 public class CanDo implements Doable { public void doThis ()
// whatever } public void doThat () // etc. implements is a reserved word Each method listed in Doable is given a definition

35 인터페이스: 예 예)DrawableCircle

36 인터페이스: 예 예제 : Drawable.java 예제 : DrawableCircle.java
1 import java.awt.Graphics; 2 3 interface Drawable { void paint(Graphics g); 5 } 예제 : DrawableCircle.java 1 import java.awt.*; 3 class DrawableCircle extends Circle implements Drawable { protected int x, y; …… public void paint(Graphics g) { g.drawOval(x-r, y-r, 2*r, 2*r); } 19 }

37 예제 : DrawApplet.java 1 import java.awt.*; 2 import java.applet.*; 3
4 public class DrawApplet extends Applet { Drawable drawable[]; 6 public void init() { drawable = new Drawable[3]; drawable[0] = new DrawableCircle(45, 45, 30); drawable[1] = new DrawableRectangle(25, 25, 40, 65); drawable[2] = new DrawableCircle(90, 70, 60); } 13 public void paint(Graphics g) { int n = drawable.length; for(int i=0; i< n; i++) { drawable[i].paint(g); } ………..

38 인터페이스 특성 인터페이스의 멤버필드는 디폴드로 static, final로 선언
값을 변경하려는 시도는 컴파일 시에 에러를 발생 인터페이스를 구현한 클래스는 인터페이스의 멤버필드를 사용할 수 있다. 인터페이스 사이의 상속 가능 클래스와 마찬가지로 키워드 extends를 사용 interface ScaledDrawable extends Drawable{…..}

39 C++

40 C++ : 상속 class B { public: int x; char f(); B(); }
class D: public B { // D derived from B int x; // D::x is added, B::x is inherited int g(); // added member function

41 C++ : Public 상속 구문 자식 클래스에서 가시성 부모클래스 public protected private 자식클래스
class <derived> : public <base> { <member-declarations> } 자식 클래스에서 가시성 부모클래스 public protected private 자식클래스 inaccesible

42 C++: Private 상속 상속된 멤버는 자식클래스에서 전용(private)이 된다. 상속된 멤버의 가시성 부모클래스
class <derived> : private <base> { <member-declarations> } 상속된 멤버의 가시성 부모클래스 public protected private 자식클래스 inaccesible

43 C++ : Virtual 함수 C++의 가상 함수(virtual function)
자식클래스에서 재정의될 수 있는 함수 모든 java 메쏘드는 virtual !! C++의 순수 가상 함수(pure virtual function) Java의 추상 메쏘드(abstract method) 자식클래스에서 정의되는 함수 가상 함수 호출 객체에 타입에 따라 동적 바인딩 된다.

44 C++ : 동적 바인딩 class B { public: }
virtual char f() { return ‘B’; } char g() { return ‘B’; } char testF { return f(); } char testG { return g(); } } class D: public B { // D derived from B char f() { return ‘D’; } char g() { return ‘D’; }

45 C++ : 동적 바인딩 main() { D d; print d.testF(), d.testG(); }

46 구현

47 객체 구현 객체는 구조체(레코드)처럼 메모리가 할당된다. 동적 바인딩 접근 가능성 검사 각 실체 변수에 대한 메모리 할당.
가상 메쏘드 테이블(Virtual method table) 이용 각 객체는 이 테이블에 대한 포인터를 갖는다. 접근 가능성 검사 접근 가능성 검사는 컴파일 시간에 이루어진다.

48 메쏘드 테이블(Method Table) 메쏘드 테이블 메쏘드 호출 구현 각 클래스마다 메쏘드 테이블이 하나씩 있다.
클래스의 모든 가상 메쏘드는 하나의 인덱스를 갖는다. 각 인덱스의 내용은 해당 메쏘드 코드의 주소 메쏘드 호출 구현 대상 객체의 메쏘드 테이블 포인터를 따라간다. 해당 인덱스의 메쏘드 주소를 따라간다. 그 주소로 점프한다.

49 메쏘드 테이블 상속과 재정의 서브클래스는 수퍼클래스의 메쏘드 테이블을 상속받는다.
메쏘드가 재정의되면, 해당 메쏘드 테이블을 갱신하다.

50 클래스와 메쏘드 테이블 Method table of A Method table of B class A {
int foo() {…} void bar() {…} }; class B extends A { float boo() {…} address of foo() address of bar() 1 Method table of A address of foo() address of bar() 1 address of boo() 2 Method table of B

51 메쏘드 호출 예 Get the method table of A foo’s id is 0
Get the address of 0th method Jump to the address A a = new A(); a.foo(); …. a = new B(); a.foo(); a.bar(); Get the method table of B foo’s id is 0 Get the address of 0th method Jump to the address Get the method table of B bar’s id is 1 Get the address of 1st method Jump to the address


Download ppt "10장 객체-지향 프로그래밍 II."

Similar presentations


Ads by Google