windows programming(3)_oop 1 object oriented programming object class instance static fields ...

39
Windows Programming(3)_OOP 1 Object Oriented Programming Object Oriented Programming Object & Class Instance & Static Fields Constructor Methods Inheritance is & as Polymorphism virtual & override method Abstract class Interface

Upload: jasmine-cook

Post on 18-Jan-2018

227 views

Category:

Documents


0 download

DESCRIPTION

Windows Programming(3)_OOP 3 객체지향 적인 접근방법 (C#) //EmployeeEx.cs using System; class Employee { public string Name; protected int hoursWorked; public Employee(string Name, int age, int hoursWorked) { this.Name = Name; this.hoursWorked = hoursWorked; } public double CalculatePay() { return (20000 * hoursWorked); // calculate pay here } class EmployeeEx { public static void Main() { Employee emp = new Employee (“ 홍길동 ", 200); //instantiation Console.WriteLine(emp.Name +” pay ::”+ emp.CalculatePay()); }

TRANSCRIPT

Page 1: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 1

Object Oriented ProgrammingObject Oriented Programming

Object & Class Instance & Static Fields Constructor Methods Inheritance is & as Polymorphism virtual & override method Abstract class Interface

Page 2: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 2

비 객체지향 적인 접근방법 비 객체지향 적인 접근방법 (c-language)(c-language)

struct Employee{

char Name[25]; // 성명double hoursWorked; // 근무시간

}void Main(){

double dTotalPay;struct EMPLOYEE * pEmp;pEmp = (struct EMPLOYEE*) malloc(sizeof(struct EMPLOYEE));if (pEmp){ pEmp -> hoursWorked = 100; strcpy(pEmp -> Name, “ 홍길동” ); dTotalPay = pEmp -> hoursWorked * 20000;

// 급여계산 = 근무시간 * 시간당 급여 printf(“Total payment for %s is %.2f”, pEmp -> Name, dTotalPay); }free(pEmp);

}

Page 3: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 3

객체지향 적인 접근방법객체지향 적인 접근방법 (C#)(C#)

//EmployeeEx.csusing System;class Employee{

public string Name;protected int hoursWorked;public Employee(string Name, int age, int hoursWorked)

{this.Name = Name;this.hoursWorked = hoursWorked;

}public double CalculatePay() { return (20000 * hoursWorked); // calculate pay here }

}class EmployeeEx{

public static void Main(){ Employee emp = new Employee (“ 홍길동 ", 200); //instantiation Console.WriteLine(emp.Name +” pay ::”+ emp.CalculatePay());}

}

Page 4: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 4

객체객체 (Object)(Object) 실 세계의 사물이나 개념을 프로그램적으로 이용할 수 있도록

표현한 소프트웨어 단위 객체의 구성요소

• 속성 (Attributes, properties, state, data, variable) 객체를 구별시키는 상태 값을 나타내는 데이터

• 행위 (Behaviors, Messages, Methods, function) 객체 내부의 속성값을 변경하거나 조작하는 기능 외부의 다른 객체에게 영향을 주거나 받는 동적인 기능

Class• 객체를 정의한 데이터형• 객체를 구성하는 속성과 행위를 프로그램적 요소인 변수와 함수로

표현 Instance

• 클래스로부터 생성된 고유한 객체 ( 메모리 할당 )

[Point 객체 예 ]상태 ( 데이터 ) : x, y 위치 값 기능 ( 함수 ) : x, y 위치 값 설정하기 , 이동하기

Page 5: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 5

은행계좌 클래스 예은행계좌 클래스 예 클래스에 데이터와 메서드 정의 일반적으로 메서드는 Public, 데이터는 Private 으로 정의

class BankAccount{ public void Withdraw(decimal amount) // 인출처리 { ... } public void Deposit(decimal amount) // 예금처리 { ... } public static InterRate(double in) // 이자계산 { ... } private decimal balance; // 잔액 private string name; // 고객명 static double interest = 0.7; // 이율}

Public methods외부 접근 가능한 객체의 행위

Private fields내부에서만 접근 가능한 데이터

Static fields객체에서 공유할 데이터

Static methodsStatic fields 만 접근가능한 행위

Page 6: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 6

Instance Instance data data & Static(class) data & Static(class) data instance data

• 객체의 현재상태를 저장할 수 있는 데이타• 객체 생성시 메모리 공간 할당

Static(class) data • 전역 데이터 , 공유 데이터• 클래스 로드 시 공간할당• 클래스 이름으로 접근

Withdraw( )

Deposit( )

balance 1000

owner “ 이몽룡”

interest 7%

Withdraw( )

Deposit( )

balance 50000

owner “ 성춘향”

interest 7%

Page 7: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 7

Static Static (class) (class) MethodsMethods

정적 ( 클래스 ) 데이터를 접근할 수 있는 메서드 Instance data 접근 불가능

InterestRate( )

interest 7%

Withdraw( )

Deposit( )

balance 10000

owner “ 이몽룡”

account account InstanceInstanceaccount classaccount class

Page 8: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 8

객체 생성객체 생성 (Instantiation)(Instantiation) new 연산자를 사용하여 객체 생성 정의된 생성자 호출

class AccountEx{ static void Main( ) { BankAccount yours = new BankAccount( ); yours.Deposit(100000); }}

yoursbalance 0

owner “”

Withdraw( )

Deposit( )

Page 9: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 9

Class Class 정의정의 class 키워드 사용 블록 내에 class members (method, data) 정의

Class members• fields : member variable, object data• methods : fields 를 조작하는 명령들• constants : 상수 • Property : smart field • Indexers : smart array• Event • Operators : 연산자 overloading

class AddClass { private int result; //datapublic int add(int a, int b){ //method

result = a + b; return(result); }}

Page 10: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 10

using System;class Field{

public const int I = 52; // 상수 , static( 정적 ) 속성 , static 을 함께 사용하면 오류

public const int J = I * 100;public int k = 100; // 객체 ( 인스턴스 ) 속성 변수 public static int m = 500; // 클래스 ( 정적 ) 변수

}class FieldsEx{ public static void Main() { Field obj = new Field();

const decimal PI = 3.141592653589M; //local 상수에는 접근 제한자 사용 안 함Console.WriteLine(" 클래스 멤버로서의 일반 상수 : {0}",Field.I);Console.WriteLine(" 클래스 멤버로서의 계산된 상수 : {0}",Field.J);Console.WriteLine(" 지역 변수로서의 상수 : {0}",PI);Console.WriteLine(" 일반 인스턴스 멤버 변수 : {0}",obj.k);Console.WriteLine(" 클래스 멤버 변수 : {0}",Field.m);}

}

Fields Fields

Page 11: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 11

ConstructorConstructor 객체 생성시 호출되는 함수 Public, 클래스명과 동일 , 반환값 없다 . Default constructor

• 객체의 모든 데이터 초기화 (zero, null, false)• 생성자가 정의되어 있으면 자동생성 안됨

생성자 정의• 매개변수를 이용하여 다양한 형태로 초기값을 설정하기 위한

생성자 정의

class BankAccount{ public BankAccount() { } public BankAccount(string name) { this.name = name; } public BankAccount(string name, int balance) {this.name = name;this.balance = balance; }…}class AccountEx{ static void Main( ) { BankAccount ba1 = new BankAccount(); BankAccount ba2 = new BankAccount(" 홍길동” ); BankAccount ba2 = new BankAccount(" 성춘향” , 10000);… }}

Page 12: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 12

메소드메소드 (Method)(Method) 객체의 동작을 정의 형식

• static : class method, static member field 를 조작하기위한 method

• abstract : 추상클래스에서 선언될 추상 메소드 • virtual : 상속관계에서 상위클래스에 정의되는 메소드 , 재정의 (override) 가 가능함을 명시하는 메소드• override : 하위클래스에서 메소드를 재 정의할 때 사용 , 상위 클래스의 virtual 메소드와 매칭

[ 접근 한정자 ] [static/abstract/virtual/override] 반환값유형 메소드명 ([ 매개변수들 ]) { ............ // 지역변수 선언 및 메소드 구현

return( 반환값 );}

Page 13: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 13

using System;class Hello { public int x; //instance field public static int y; //static field void foo() { // instance 메소드 x = 1; // this.x = 1 y = 1; // Hello.y = 1 } static void foo2() { // static 메소드 Hello ex = new Hello(); ex.x = 1; // x = 1; // Error, Object reference y = 1; // OK, } public static string addString(string str) { str += " World!!"; return str; }}

class HelloEx {public static void Main() { Hello ex = new Hello(); ex.x = 1; // OK, // ex.y = 1; // Error, static member field Hello.y = 1; // OK, Console.WriteLine("{0}, {1}", ex.x, Hello.y); string str = "Hello"; Console.WriteLine(Hello.addString(str)); // 출력값 , Hello World!! }}

Instance, static method Instance, static method 예예

Page 14: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 14

class Test{ int value = 100; public void setValue(int v) { value = v; } public Test copy1() {

Test t = new Test();return (t);

} public Test copy2() { return (this); } public void print(string name) { Console.WriteLine ("name={0}, value={1}", name, value); }}

Method return Method return 예예 class MethodreturnEx{ public static void Main() { Test t1 = new Test(); Test t2 = t1.copy1(); //new Console.WriteLine ("copy1 t1(new) to t2"); t1.print("t1"); t2.print("t2"); t1.setValue(50); Console.WriteLine ("t1.setValue(50)"); t1.print("t1"); t2.print("t2"); t2.setValue(200); Console.WriteLine ("t2.setValue(200)"); t1.print("t1"); t2.print("t2"); Console.WriteLine ("copy2 t1(this) to t3"); Test t3 = t1.copy2(); //this copy t1.print("t1"); t3.print("t3"); t3.setValue(1000); Console.WriteLine ("t3.setValue(1000)"); t1.print("t1"); t3.print("t3"); Console.ReadLine (); }}

Page 15: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 15

Parameter PassingParameter Passing Pass by value

• 값에 의한 전달 방식 • Method(int x, int y)

Pass by reference• 참조에 의한 전달방식 • ref 키워드 사용 ( 메소드 정의 / 메소드 호출 )• 호출 전에 매개변수 초기화 • 메모리가 할당된 참조 형 데이터를 매개변수로 사용• Method(ref int x, ref int y), Mehod (object a)

Pass by output• 출력에 의한 전달방식 • 값을 반환 받을 때만 사용• out 키워드 사용• Method(out int x, out int y)

Page 16: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 16

Parameter passing Parameter passing 예 예 using System;class ParameterPass {

static int Sum( int a, int b) { int sum = 0; sum = a + b; return (sum); } static void Swap(int a, int b) { int t = a; a = b; b = t; } static void refSwap(ref int a, ref int b) { int t = a; a = b; b = t; } static void Divide(int a, int b, out int

result, out int remainder)

{ result = a / b; remainder = a % b; }

static void Main() { int x = 1; int y = 2; int result, remainder; // Initialization is not required Console.WriteLine(" x = {0}, y = {1}", x, y); Console.WriteLine(“call Sum: x = {0}, y = {1}, sum ={2}", x, y, Sum(x,y));

Swap(x, y); Console.WriteLine(“call Swap: x = {0}, y = {1}", x, y);

refSwap(ref x, ref y); Console.WriteLine(“call refSwap: x = {0}, y = {1}", x, y);

Divide(x, y, out result, out remainder); Console.WriteLine(“call Divide: x = {0}, y = {1}, result={2}, remainder={3}", x, y, result, remainder); }}

Page 17: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 17

//out 을 사용한 Pass by referenceusing System; class ArrayPass { static public void FillArray(out int[] myA) { // Initialize the array: myA = new int[5] {1, 2, 3, 4, 5}; }

static public void Main() { int[] myArray; // Initialization is not

required

// Pass the array to the call using out: FillArray(out myArray);

// Display the array elements: Console.WriteLine("Array elements

are:"); for (int i=0; i < myArray.Length; i++) Console.WriteLine(myArray[i]); }}

// 배열 객체를 사용한 Pass by referenceusing System; class ArrayPass { static public void FillArray(int[] myA) {

for (int i=0; i < myA.Length; i++)myA[i] = i + 10;

//fill the array elements }

static public void Main() { int[] myArray = new int[5]; FillArray(myArray); //method call

// Display the array elements: Console.WriteLine("Array elements

are:"); for (int i=0; i < myArray.Length; i++) Console.WriteLine(myArray[i]); }}

Page 18: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 18

Stack

myArray

myA

FillArray(myArray);

Stack Heap

myArray

myA

FillArray(out myArray);

Heap

Pass by value & Pass by output Pass by value & Pass by output

Page 19: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 19

InheritanceInheritance 이미 존재하는 클래스를 구체화하여 새로운 클래스 생성 재사용성 , 확장성 클래스의 계층 구조 생성

• 상속 받은 interface 사용 보장 (upcasting) 상위클래스 (base class) 의 모든 멤버필드와 메소드를 하위클래스

(derived class) 로 상속 “base” 연산자로 상위 객체 접근 클래스를 정의 할 때 : ( 콜론 ) 을 사용하여 상속관계 표시 Class <derivedClass> : <baseClass>

class Shape{ ...}class Circle: Shape{ ...}

Page 20: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 20

Motivation: repeated codeMotivation: repeated code

class Student{ string name; int age; public void Birthday() { age++; }

int id;}

repeated codeclass Employee{ string name; int age; public void Birthday() { age++; }

double salary;}

Page 21: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 21

Inheritance syntaxInheritance syntax• 상위 클래스에 공통멤버 정의• 하위 클래스에 필요한 멤버 추가

class Person{ string name; int age; public void Birthday() { age++; }}

common code

class Student : Person{ int id;}

Student member

class Employee : Person{ double salary;}

Employee member

Page 22: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 22

Memory allocationMemory allocation

class Person{ string name; int age; ...}

class Student : Person{ int id; ...}

Student s = new Student();

name age

s

basefields

derivedfield

하위객체 생성시 상위객체도 생성되어 데이터의 메모리 할당

id

Page 23: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 23

상위클래스 멤버 사용상위클래스 멤버 사용

class Person{ public void Birthday() { age++; } ...}

class Student : Person{ ...}

Student s = new Student();

s.Birthday();

basemethod

상속된 객체에서 상위 객체의 메서드 호출

Page 24: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 24

Base / Base / DDeriveerivedd ConversionsConversions 하위 클래스가 상위클래스로의 형 변환 가능 (upcasting) 상위클래스가 하위클래스로의 형 변환

• Explicit ( 명시적 형 변환 연산자 필요 )• 실행 시 참조변수가 가리키는 실제 객체의 데이터 형 검사• 실패하는 경우 “ InvalidCastException” 발생

public class MyBaseC {..}

public class MyDerivedC : MyBaseC {…}

Class ex{

MyBaseC c1 = new MyBaseC();

MyDerivedC d1 = new MyDerivedC();

c1 = d1; //upcasting

d1 = (MyDerivedC) c1; //downcasting

}

Page 25: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 25

is & as Operatoris & as Operator is

• 데이터의 형 변환이 가능하면 true 반환 as

• 객체 사이의 형 변환 연산자• 오류 발생시 exception 발생 없이 null 반환

Bird b;if (a is Bird) b = (Bird) a; // Safeelse Console.WriteLine("Not a Bird");

Bird b = a as Bird; // Convertif (b == null)

Console.WriteLine("Not a bird");

Page 26: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 26

constructor-initializer constructor-initializer base(argument-listopt) : 상속 받은 상위 클래스의 생성자 호출 this(argument-listopt) : 자기자신에서 정의한 다른 생성자 호출

using System;

class A{public A() {

Console.WriteLine("A");}

}class B : A{ //A class 에서 상속

public B() { //== public B():base()Console.WriteLine("B");

}public B(int foo) : this() { //B() 호출

Console.WriteLine("B({0})“, foo);}

}class DefaultInitializerApp{

public static void Main() {B b1 = new B();B b2 = new B(100);

}}

ABABB(100)

Page 27: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 27

using System;class A{

public int value;public A() : this(100) { // 초기값 리스트를 사용한 생성자

Console.WriteLine("A");}public A(int foo) {

value = foo; Console.WriteLine("A = {0}", value);}

}class B : A{ public B() // 상위 클래스의 기본 생성자를 암시적으로 호출

{Console.WriteLine("B");

}public B(int foo) :base(foo) // 상위 클래스의 생성자를 명확하게

지시 {

Console.WriteLine("B = {0}", foo);}

}class DerivedInitializerApp{

public static void Main(){

B b1 = new B();B b2 = new B(42);

}}

A = 100ABA = 42B = 42

constructor-initializer constructor-initializer 예예

Page 28: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 28

PolymorphismPolymorphism 상위 클래스에서 선언된 method 를 하위클래스에서 구현 (Override) 실행시간에 새로 정의된 Override 된 멤버의 내용으로 처리 (late

binding)

Object

Shape

Circle

Rectangle

Void Draw()

Void Draw()

Void Draw()

Page 29: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 29

Virtual MethodsVirtual Methods Virtual method

• 하위클래스에서 재정의가 가능하도록 메소드를 정의• Static 과 함께 사용할 수 없다 .• Private 접근 제한자를 가질 수 없다 .

Virtual method 정의class Shape{ ... public string Name( ) { ... } public virtual void Draw( ) { ... } }

Page 30: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 30

Overriding MethodsOverriding Methods 상속된 가상 메서드 (virtual method) 를 구현 ( 재정의 ) “override” 키워드 사용 virtual method 와 override method 는 이름 , 접근 제한

자 , 반환 값 , 매개변수리스트가 동일해야 한다 . static,private 을 override 와 함께 사용할 수 없다 .

class Shape{ ... public string Name( ) { ... } public virtual void Draw( ) { ... } }class Circle: Shape{ ... public override string Name( ) { ... } //X public override void Draw( ) { ... } //O}

Page 31: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 31

//inheritance & polymorphism (PolymorphismEx.cs)public class Shape{

public virtual void Draw() {Console.WriteLine("Shape Draw");

}

}public class Circle : Shape {

public override void Draw() {Console.WriteLine("Circle Draw");

}}public class Rectangle : Shape {

public override void Draw() {Console.WriteLine("Rectangle Draw");

}}public class PolymorphismEx{

public static void Main() {Shape s = new Shape();s.Draw(); s = new Circle();s.Draw(); s = new Rectangle();s.Draw();

} }

Shape DrawCircle DrawRectangle Draw

Page 32: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 32

//inheritance & pholymorphism (EmployeeInheEx.cs)class Employee{

public string Name;protected int age;protected int hoursWorked;public Employee(string Name, int age, int hoursWorked)

{this.Name = Name;this.age = age;this.hoursWorked = hoursWorked;

}public virtual double CalculatePay() { return (20000 * hoursWorked); // calculate pay }

}class SalariedEmployee : Employee // 상속 {

protected int basePay; public SalariedEmployee(string Name,int age, int hoursWorked)

: base(Name, age, hoursWorked) // 상위 클래스의 생성자 를 명시적으로 호출

{ basePay = 1000000;}

public override double CalculatePay() //method overriding{

return (basePay + 20000 * hoursWorked); // pay calculate }}

Page 33: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 33

public class PayMan{ public static void Main() { Employee[] empList = { new Employee(" 홍길동 ", 22, 30), new SalariedEmployee(" 성춘향 ", 22, 30) }; foreach (Employee emp in empList) Console.WriteLine(">> 성명 :{0}, 급여 :{1}", emp.Name, emp.CalculatePay()); Console.ReadKey(); }}

Page 34: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 34

Abstract ClassesAbstract Classes 추상 클래스

• 개체들의 표준을 추상화 한 클래스• 상속관계에서 가장 상위에 존재

abstract 키워드를 사용하여 정의

abstract class Shape{ ...}class Test{ static void Main( ) { new Shape( ); }}

추상 클래스는 인스턴스를 생성할 수 없다 .

Page 35: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 35

Abstract MethodsAbstract Methods 추상 클래스만이 추상 메소드를 가질 수 있다 . 추상 메소드는 암시적으로 가상 메소드 virtual 키워드사용 불가 메소드 이름 앞에 “ abstract” 키워드 사용 상속받는 클래스에서 반드시 재정의

abstract class Ticket{ public virtual string StartTime( ) { ... } public abstract int Fare( );}class BusTicket: Ticket{ public override string StartTime( ) { ... } public override int Fare( ) { ... }}

Page 36: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 36

//abstract class/abstract method 예 (AbstractClassEx.cs)abstract class printer{

public abstract void print();}abstract class HPprinter : printer{

public abstract void selfTest();}class HP640 : HPprinter{

public override void print(){

Console.WriteLine(" 문서를 출력합니다 .");}

public override void selfTest(){

Console.WriteLine(" 프린터를 자가 진단합니다 .");}

}class AbstractClassEx{

public static void Main(){

HP640 myprinter = new HP640();myprinter.print();myprinter.selfTest();

}}

Page 37: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 37

InterfacesInterfaces

행동적인 특성 ( 메서드 , 속성 , 인덱서 , 이벤트 ) 만을 정의 다중상속을 구현하기 위한 방법으로 사용 “interface” 키워드를 사용하여 선언

interface Itoken : IBase{ int LineNumber( ); string Name( );} 메소드는 구현부분이

없이 ‘ ; ‘ 으로 처리

관례적으로 “ I” 접두어 사용 Interface 상속

public

Page 38: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 38

Class & InterfacesClass & Interfaces 클래스 / 인터페이스 관계

• 클래스 & 클래스 : 상속관계• 클래스 & 인터페이스 : 구현관계• 인터페이스 & 인터페이스 : 상속관계

클래스 & 인터페이스 선언 예interface IMyInterface: IBase1, IBase2 { void MethodA(); void MethodB(); } class Class1: Iface1, Iface2 { // class members , implementing interface }

class ClassA: BaseClass, Iface1, Iface2 { // class members, implementing interface }

클래스와 인터페이스를 함께 상속 받는 경우 기본 클래스가 처음에 위치

Page 39: Windows Programming(3)_OOP 1 Object Oriented Programming  Object  Class  Instance  Static  Fields  Constructor  Methods  Inheritance  is  as

Windows Programming(3)_OOP 39

//interface & Inheritance (IntegerfaceEx.cs)

using System;interface IScalable{ void ScaleX(float factor); void ScaleY(float factor);}public class DiagramObject{ public DiagramObject() {}}public class TextObject: DiagramObject, IScalable{ public TextObject(string text) { this.text = text; } // implementing IScalable.ScaleX() public void ScaleX(float factor) { Console.WriteLine("ScaleX: {0} {1}", text, factor); } // implementing IScalable.ScaleY() public void ScaleY(float factor) { Console.WriteLine("ScaleY: {0} {1}", text, factor); } private string text;}

/*DiagramObject 로부터 상속된 클래스

생성 객체를 array 로 처리 */class InterfaceEx { public static void Main() { DiagramObject[] dArray = new DiagramObject[10]; dArray[0] = new DiagramObject(); dArray[1] = new TextObject("Text

Dude"); dArray[2] = new TextObject("Text

Backup"); /* array gets initialized here, with

classes that derive from DiagramObject. Some of them implement IScalable. */

foreach (DiagramObject d in dArray) { if (d is IScalable) { IScalable scalable = (IScalable)

d; scalable.ScaleX(0.1F); scalable.ScaleY(10.0F); } //if } //foreach } //main} //class