Presentation is loading. Please wait.

Presentation is loading. Please wait.

Windows Programming(3)_OOP 1 Object Oriented Programming  Object & Class  Instance & Static  Fields  Constructor  Methods  Inheritance  is & as.

Similar presentations


Presentation on theme: "Windows Programming(3)_OOP 1 Object Oriented Programming  Object & Class  Instance & Static  Fields  Constructor  Methods  Inheritance  is & as."— Presentation transcript:

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

2 Windows Programming(3)_OOP 2 비 객체지향 적인 접근방법 (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); }

3 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()); }

4 Windows Programming(3)_OOP 4 객체 (Object)  실 세계의 사물이나 개념을 프로그램적으로 이용할 수 있도록 표현 한 소프트웨어 단위  객체의 구성요소 속성 (Attributes, properties, state, data, variable)  객체를 구별시키는 상태 값을 나타내는 데이터 행위 (Behaviors, Messages, Methods, function)  객체 내부의 속성값을 변경하거나 조작하는 기능  외부의 다른 객체에게 영향을 주거나 받는 동적인 기능  Class 객체를 정의한 데이터형 객체를 구성하는 속성과 행위를 프로그램적 요소인 변수와 함수로 표 현  Instance 클래스로부터 생성된 고유한 객체 ( 메모리 할당 ) [Point 객체 예 ] 상태 ( 데이터 ) : x, y 위치 값 기능 ( 함수 ) : x, y 위치 값 설정하기, 이동하기

5 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 외부 접근 가능한 객체의 행위 Public methods 외부 접근 가능한 객체의 행위 Private fields 내부에서만 접근 가능한 데이터 Private fields 내부에서만 접근 가능한 데이터 Static fields 객체에서 공유할 데이터 Static fields 객체에서 공유할 데이터 Static methods Static fields 만 접근 가능한 행위 Static methods Static fields 만 접근 가능한 행위

6 Windows Programming(3)_OOP 6 Instance data & Static(class) data  i nstance data 객체의 현재상태를 저장할 수 있는 데이타 객체 생성시 메모리 공간 할당  Static(class) data 전역 데이터, 공유 데이터 클래스 로드 시 공간할당 클래스 이름으로 접근 Withdraw( ) Deposit( ) balance 1000 owner “ 이몽룡 ” interest 7% Withdraw( ) Deposit( ) balance 50000 owner “ 성춘향 ” interest 7%  

7 Windows Programming(3)_OOP 7 Static (class) Methods  정적 ( 클래스 ) 데이터를 접근할 수 있는 메서드  Instance data 접근 불가능 InterestRate( ) interest 7% Withdraw( ) Deposit( ) balance 10000 owner “ 이몽룡 ” account Instance account class  

8 Windows Programming(3)_OOP 8 객체 생성 (Instantiation)  new 연산자를 사용하여 객체 생성  정의된 생성자 호출 class AccountEx { static void Main( ) { BankAccount yours = new BankAccount( ); yours.Deposit(100000); } yours balance 0 owner “” Withdraw( ) Deposit( )

9 Windows Programming(3)_OOP 9 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; //data public int add(int a, int b){ //method result = a + b; return(result); }

10 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

11 Windows Programming(3)_OOP 11 Constructor  객체 생성시 호출되는 함수  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); … }

12 Windows Programming(3)_OOP 12 메소드 (Method)  객체의 동작을 정의  형식 static : class method, static member field 를 조작하기위한 method abstract : 추상클래스에서 선언될 추상 메소드 virtual : 상속관계에서 상위클래스에 정의되는 메소드, 재정의 (override) 가 가능함을 명시하는 메소드 override : 하위클래스에서 메소드를 재 정의할 때 사용, 상위 클래스의 virtual 메소드와 매칭 [ 접근 한정자 ] [static/abstract/virtual/override] 반환값유형 메소드명 ([ 매개변수들 ]) {............ // 지역변수 선언 및 메소드 구현 return( 반환값 ); }

13 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 예

14 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 예 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 (); }

15 Windows Programming(3)_OOP 15 Parameter 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)

16 Windows Programming(3)_OOP 16 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); }

17 Windows Programming(3)_OOP 17 //out 을 사용한 Pass by reference using 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 reference using 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]); }

18 Windows Programming(3)_OOP 18 Stack myArray myA FillArray(myArray); Stack Heap myArray myA FillArray(out myArray); Heap Pass by value & Pass by output

19 Windows Programming(3)_OOP 19 Inheritance  이미 존재하는 클래스를 구체화하여 새로운 클래스 생성  재사용성, 확장성  클래스의 계층 구조 생성 상속 받은 interface 사용 보장 (upcasting)  상위클래스 (base class) 의 모든 멤버필드와 메소드를 하위클래스 (derived class) 로 상속  “ base ” 연산자로 상위 객체 접근  클래스를 정의 할 때 : ( 콜론 ) 을 사용하여 상속관계 표시 Class : class Shape {... } class Circle: Shape {... }

20 Windows Programming(3)_OOP 20 Motivation: repeated code class Student { string name; int age; public void Birthday() { age++; } int id; } repeated code class Employee { string name; int age; public void Birthday() { age++; } double salary; }

21 Windows Programming(3)_OOP 21 Inheritance 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

22 Windows Programming(3)_OOP 22 Memory allocation class Person { string name; int age;... } class Student : Person { int id;... } Student s = new Student(); name age s base fields derived field  하위객체 생성시 상위객체도 생성되어 데이터의 메모리 할당 id

23 Windows Programming(3)_OOP 23 상위클래스 멤버 사용 class Person { public void Birthday() { age++; }... } class Student : Person {... } Student s = new Student(); s.Birthday(); base method 상속된 객체에서 상위 객체의 메서드 호출

24 Windows Programming(3)_OOP 24 Base / Derived Conversions  하위 클래스가 상위클래스로의 형 변환 가능 (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 }

25 Windows Programming(3)_OOP 25 is & as Operator  is 데이터의 형 변환이 가능하면 true 반환  as 객체 사이의 형 변환 연산자 오류 발생시 exception 발생 없이 null 반환 Bird b; if (a is Bird) b = (Bird) a; // Safe else Console.WriteLine("Not a Bird"); Bird b = a as Bird; // Convert if (b == null) Console.WriteLine("Not a bird");

26 Windows Programming(3)_OOP 26 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); } A B A B B(100)

27 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 = 100 A B A = 42 B = 42 constructor-initializer 예

28 Windows Programming(3)_OOP 28 Polymorphism  상위 클래스에서 선언된 method 를 하위클래스에서 구현 (Override)  실행시간에 새로 정의된 Override 된 멤버의 내용으로 처리 (late binding) Object Shape Circle Rectangle Void Draw()

29 Windows Programming(3)_OOP 29 Virtual Methods  Virtual method 하위클래스에서 재정의가 가능하도록 메소드를 정의 Static 과 함께 사용할 수 없다. Private 접근 제한자를 가질 수 없다.  Virtual method 정의 class Shape {... public string Name( ) {... } public virtual void Draw( ) {... }

30 Windows Programming(3)_OOP 30 Overriding 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 }

31 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 Draw Circle Draw Rectangle Draw

32 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 } }

33 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(); }

34 Windows Programming(3)_OOP 34 Abstract Classes  추상 클래스 개체들의 표준을 추상화 한 클래스 상속관계에서 가장 상위에 존재  abstract 키워드를 사용하여 정의 abstract class Shape {... } class Test { static void Main( ) { new Shape( ); } 추상 클래스는 인스턴스를 생성할 수 없다. 

35 Windows Programming(3)_OOP 35 Abstract 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( ) {... } }

36 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(); }

37 Windows Programming(3)_OOP 37 Interfaces  행동적인 특성 ( 메서드, 속성, 인덱서, 이벤트 ) 만을 정의  다중상속을 구현하기 위한 방법으로 사용  “ interface ” 키워드를 사용하여 선언 interface Itoken : IBase { int LineNumber( ); string Name( ); } 메소드는 구현부분이 없이 ‘; ‘ 으로 처리 관례적으로 “I” 접두어 사용 Interface 상속 public

38 Windows Programming(3)_OOP 38 Class & 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 } 클래스와 인터페이스를 함께 상속 받는 경우 기본 클래스가 처음에 위치

39 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


Download ppt "Windows Programming(3)_OOP 1 Object Oriented Programming  Object & Class  Instance & Static  Fields  Constructor  Methods  Inheritance  is & as."

Similar presentations


Ads by Google