Chương 9 – Lập trình hướng đối tượng trong C# docx

130 2.5K 16
Chương 9 – Lập trình hướng đối tượng trong C# docx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chương – Lập trình hướng đối tượng C# Outline         9.1 Lớp đối tượng - Class and Objects 9.2 Giao diện - Interfaces 9.3 Quyền truy cập - Modifiers 9.4 Thuộc tính - Properties 9.5 Phương thức – Methods 9.6 Sự kiện hàm đại diện- Events and Delegates 9.7 Tính kế thừa – Inheritance Các lớp sở lớp dẫn xuất Protected Members Phương thức khởi tạo: Constructors hủy Destructors lớp dẫn xuất 9.8 Tính đa hình – Polymorphism Lớp Abstract phương thức Nạp chồng toán tử 9.1 Lớp đối tượng - Class and Objects  Cơ sở lập trình hướng đối tượng gắn liền với đời định nghĩa lớp đối tượng  Lập trình hướng đối tượng tư tưởng lập trình liệu ( data ) hàm ( functions ) đóng gói lớp  Một đối tượng thể ( instance ) lớp có thành phần liệu riêng Các đối tượng thể lớp có “ khung “ lớp tạo  Phân loại lớp : Có thể phân loại lớp dựa theo nhiều tiêu chí khác :  Lớp cha lớp : phân loại theo tính kế thừa  Lớp nội lớp ngoại : phân loại theo tính chứa đựng  Lớp trừu tượng lớp cài đặt : phân loại theo chức 9.1 Khai báo lớp  Cấu trúc : [Bổ từ truy cập] class [:] [Tên_lớp_cha] Trong thành phần nằm [] không bắt buộc  Bổ từ truy cập : Xác định phạm vi sử dụng lớp  class : Từ khoá khai báo lớp  Tên_lớp : Là tên lớp không chứa dấu cách phải bắt đầu kí tự  “ : “ : Thể tính kế thừa  Tên_lớp_cha : Tên lớp cha mà lớp kế thừa từ 9.1 Khởi tạo đối tượng  Khởi tạo ( Instantiate ) đối tượng từ lớp cấp phát nhớ cho đối tượng vùng nhớ Heap Một đối tượng khai báo chưa khởi tạo chưa cấp phát nhớ  Cách khởi tạo đối tượng C# giống với Java VB.Net = new ( Các tham số có ) 9.1 Phương thức khởi tạo - Constructor   Constructor phương thức đặc biệt lớp Dùng để khởi tạo đối tượng thiết lập liệu ban đầu lớp  Constructor có tên với tên lớp khơng có giá trị trả  Constructor nạp chồng  Constructor phải sử dụng với bổ từ truy cập public  Constuctor C# giống hệt constructor Java  Cú pháp : ● public () [ : base () ] { // Đặt mã bạn vào } ● public ( tham số ) [ : base( tham số ) ] { // Đặt mã bạn vào } 9.1 Phương thức khởi tạo - Constructor  base từ khoá mặc định C# ( me VB.Net super Java ) để lớp cha ( có ) lớp xét  Trong phương thức khởi dựng lớp gọi phương thức khởi dựng lớp cha thơng qua từ khố base ● public ( ) [: base () ] ●public ( tham số ) [ : base( tham số ) ]  Ngoài , phương thức khởi dựng , ta cịn gọi phương thức khởi dựng nạp chồng khác lớp với từ khoá this ● public ( tham số ) [ : this ( tham số ) ] 9.1 Phương thức khởi tạo - Constructor  Trong lớp , Constructor C# sử dụng constructor mặc định ( không chứa tham số ) khởi tạo biến thành viên với giá trị mặc định :  Các biến giá trị số gán  Các biến đối tượng gán null  Ta có static constructor ( phương thức khởi tạo tĩnh ) Đây phương thức thực lần đối tượng lớp Instantiate Tác dụng static constructor giúp ta khởi tạo giá trị cho biến thành phần kiểu static lớp 9.1 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 // Time1.cs // Class Time1 maintains time in 24-hour format using System; Khởi tạo mặc định instance variables Private // Time1 class definition public class Time1 : Object { private int hour; // 0-23 private int minute; // 0-59 private int second; // 0-59 Time1.cs Phương thức SetTime Tính hiệu lực tham số // Time1 constructor initializes instance variables to // zero to set default time to midnight public Time1() { SetTime( 0, 0, ); } // Set new time value in 24-hour format Perform validity // checks on the data Set invalid values to zero public void SetTime( int hourValue, int minuteValue, int secondValue ) { hour = ( hourValue >= && hourValue < 24 ) ? hourValue : 0; minute = ( minuteValue >= && minuteValue < 60 ) ? minuteValue : 0; second = ( secondValue >= && secondValue < 60 ) ? secondValue : 0; } 9.1 Time1.cs 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 // convert time to universal-time (24 hour) format string public string ToUniversalString() { return String.Format( "{0:D2}:{1:D2}:{2:D2}", hour, minute, second ); } // convert time to standard-time (12 hour) format string public string ToStandardString() { return String.Format( "{0}:{1:D2}:{2:D2} {3}", ( ( hour == 12 || hour == ) ? 12 : hour % 12 ), minute, second, ( hour < 12 ? "AM" : "PM" ) ); } } // end class Time1 Giờ theo định dạng quốc tế Giờ có định dạng chuẩn 9.1 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 // TimeTest1.cs // Demonstrating class Time1 using System; using System.Windows.Forms; Gọi khởi tạo thời gian mặc định TimeTest1.cs // TimeTest1 uses creates and uses a Time1 object class TimeTest1 Gọi phương thức { SetTime để thiết lập // main entry point for application static void Main( string[] args ) thời gian với tham { số hợp lệ Time1 time = new Time1(); // calls Time1 constructor string output; // assign string representation of time to output output = "Initial universal time is: " + time.ToUniversalString() + Gọi phương "\nInitial standard time is: " + time.ToStandardString(); SetTime với // attempt valid time settings time.SetTime( 13, 27, ); thức tham số hợp lệ // append new string representations of time to output output += "\n\nUniversal time after SetTime is: " + time.ToUniversalString() + "\nStandard time after SetTime is: " + time.ToStandardString(); // attempt invalid time settings time.SetTime( 99, 99, 99 ); 9.1 Point2.cs 63 64 65 66 67 68 69 70 71 72 73 // override property Name from class Point2 public override string Name { get { return "Circle2"; } } } // end class Circle2 Đè chồng lên thuộc tính đọc Name 9.8 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // Fig 10.7: Cylinder2.cs // Cylinder2 inherits from class Circle2 and overrides key members using System; // Cylinder2 inherits from class Circle2 public class Cylinder2 : Circle2 { private double height; // Cylinder2 height Cylinder2.cs // default constructor public Cylinder2() { // implicit call to Circle2 constructor occurs here } // constructor public Cylinder2( int xValue, int yValue, double radiusValue, double heightValue ) : base( xValue, yValue, radiusValue ) { Height = heightValue; } // property Height public double Height { get { return height; } Lớp Cylinder2 thu từ Circle2 set { // ensure non-negative height value if ( value >= ) height = value; 9.8 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 } } Chồng lên thuộc tính đọc Name // calculate Cylinder2 area public override double Area() { return * base.Area() + base.Circumference() * Height; } Cylinder2.cs // calculate Cylinder2 volume public override double Volume() { return base.Area() * Height; } // return string representation of Circle2 object public override string ToString() { return base.ToString() + "; Height = " + Height; } // override property Name from class Circle2 public override string Name { get Chồng lên việc thực { lớp Circle2 return "Cylinder2"; } } Chồng lên việc thực tính } // end class Cylinder2 tính diện tích Area thể tích volume lớp Shape 9.8 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // Fig 10.8: AbstractShapesTest.cs // Demonstrates polymorphism in Point-Circle-Cylinder hierarchy using System; using System.Windows.Forms; Dùng tham chiếu Tạo chiếu tới Shape mảngđối đối tượng public class AbstractShapesTest lớp Shapetham chiếu tượng Point2 { Dùng public static void Main( string[] args ) Dùng chiếu tới đối Shape tham chiếu { Shape chiếu tượng Cylinder2 // instantiate Point2, Circle2 and Cylinder2 objects tới đối Point2 point = new Point2( 7, 11 ); tượng Circle2 Circle2 circle = new Circle2( 22, 8, 3.5 ); Cylinder2 cylinder = new Cylinder2( 10, 10, 3.3, 10 ); // create empty array of Shape base-class references Shape[] arrayOfShapes = new Shape[ ]; // arrayOfShapes[ ] refers to Point2 object arrayOfShapes[ ] = point; // arrayOfShapes[ ] refers to Circle2 object arrayOfShapes[ ] = circle; // arrayOfShapes[ ] refers to Cylinder2 object arrayOfShapes[ ] = cylinder; string output = point.Name + ": " + point + "\n" + circle.Name + ": " + circle + "\n" + cylinder.Name + ": " + cylinder; AbstractShapesTest.cs 9.8 31 32 33 34 35 36 37 38 39 40 41 42 // display Name, Area and Volume for each object // in arrayOfShapes polymorphically foreach( Shape shape in arrayOfShapes ) { output += "\n\n" + shape.Name + ": " + shape + "\nArea = " + shape.Area().ToString( "F" ) + "\nVolume = " + shape.Volume().ToString( "F" ); } MessageBox.Show( output, "Demonstrating Polymorphism" ); } } Dùng vòng lặp foreach để truy cập vào phần tử mảng AbstractShapesTest.cs Tin vào tính đa hình để gọi phiên thích hợp phương thức 9.8 9.8.2 Nạp chồng toán tử  C# chứa nhiều toán tử (như + - ) định nghĩa cho vài kiểu liệu  Thường phải dùng toán tử với kiểu liệu người dùng định nghĩa(ví dụ với lớp số phức )  Những ký hiệu toán tử mang tính trực giác nhiều việc gọi phương thức  C# cho phép người dùng nạp chồng toán tử cho phù hợp ngữ cảnh sử dụng 9.8 9.8.2 Nạp chồng toán tử  Phương thức xác định hành động diễn toán tử nạp chồng  Dạng: public static Kiểu-trả-về operator toán-tử-được-nạp-chồng( tham số)  Các phương thức phải khai báo dạng public static  Kiểu trả kiểu thu sau thực tính phép tốn nạp chồng  Từ khoá operator theo sau kiểu trả cho thấy phương thức xác định toán tử nạp chồng  Phần cuối thơng tin tốn tử nạp chồng(như +, -, *, )  Nếu phép tốn ngơi,một tham số phải xác định,nếu tốn tử hai ngơi,phải hai tham số khai báo 9.8 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // Fig 10.26: ComplexNumber.cs // Class that overloads operators for adding, subtracting // and multiplying complex numbers public class ComplexNumber { private int real; private int imaginary; // default constructor public ComplexNumber() {} ComplexNumber.cs Thuộc tính Real cho phép truy cập vào phần thực số phức // constructor public ComplexNumber( int a, int b ) { Real = a; Định nghĩa lớp số Imaginary = b; ComplexNumber } phức // return string representation of ComplexNumber public override string ToString() { return "( " + real + ( imaginary < ? " - " + ( imaginary * -1 ) : " + " + imaginary ) + "i )"; } // property Real public int Real { get { return real; } 9.8 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 set { real = value; } } // end property Real // property Imaginary public int Imaginary { get { return imaginary; } Chồng chập toán tử cộng(+) cho lớp số phức ComplexNumbers set { imaginary = value; } } // end property Imaginary ComplexNumber.cs Thuộc tính Imaginary cho phép truy cập vào phần ảo số phức // overload the addition operator public static ComplexNumber operator + ( ComplexNumber x, ComplexNumber y ) { return new ComplexNumber( x.Real + y.Real, x.Imaginary + y.Imaginary ); } 9.8 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 // provide alternative to overloaded + operator // for addition public static ComplexNumber Add( ComplexNumber x, ComplexNumber y ) { Phương thức Subtract – cung cấp return x + y; khả cho toán tử trừ } // overload the subtraction operator Chồng chập toán tử public static ComplexNumber operator - ( cho lớp số phức ComplexNumber x, ComplexNumber y ) ComplexNumbers { return new ComplexNumber( x.Real - y.Real, x.Imaginary - y.Imaginary ); } ComplexNumber.cs nhân (*) // provide alternative to overloaded - operator // for subtraction public static ComplexNumber Subtract( ComplexNumber x, ComplexNumber y ) { Phương thức Add – cung cấp return x - y; khả khác cho toán tử } cộng // overload the multiplication operatorChồng chập toán tử public static ComplexNumber operator * cho lớp số phức ( ComplexNumber x, ComplexNumber y ) ComplexNumbers { return new ComplexNumber( x.Real * y.Real - x.Imaginary * y.Imaginary, x.Real * y.Imaginary + y.Real * x.Imaginary ); } trừ (-) 9.8 ComplexNumber.cs 98 99 100 101 102 103 104 105 106 107 // provide alternative to overloaded * operator // for multiplication public static ComplexNumber Multiply( ComplexNumber x, ComplexNumber y ) { return x * y; } } // end class ComplexNumber Phương thức Multiply – cung cấp khả khác cho toán tử nhân 9.8 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 // Fig 10.27: OperatorOverloading.cs // An example that uses operator overloading using using using using using using System; System.Drawing; System.Collections; System.ComponentModel; System.Windows.Forms; System.Data; OperatorOverloading.cs public class ComplexTest : System.Windows.Forms.Form { private System.Windows.Forms.Label realLabel; private System.Windows.Forms.Label imaginaryLabel; private System.Windows.Forms.Label statusLabel; private System.Windows.Forms.TextBox realTextBox; private System.Windows.Forms.TextBox imaginaryTextBox; private private private private private System.Windows.Forms.Button System.Windows.Forms.Button System.Windows.Forms.Button System.Windows.Forms.Button System.Windows.Forms.Button firstButton; secondButton; addButton; subtractButton; multiplyButton; private ComplexNumber x = new ComplexNumber(); private ComplexNumber y = new ComplexNumber(); [STAThread] static void Main() { Application.Run( new ComplexTest() ); } 9.8 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 private void firstButton_Click( object sender, System.EventArgs e ) { x.Real = Int32.Parse( realTextBox.Text ); x.Imaginary = Int32.Parse( imaginaryTextBox.Text ); realTextBox.Clear(); imaginaryTextBox.Clear(); statusLabel.Text = "First Complex Number is: " + x; } OperatorOverloading.cs Dùng toán tử cộng để cộng hai số phức private void secondButton_Click( object sender, System.EventArgs e ) { y.Real = Int32.Parse( realTextBox.Text ); y.Imaginary = Int32.Parse( imaginaryTextBox.Text ); realTextBox.Clear(); imaginaryTextBox.Clear(); statusLabel.Text = "Second Complex Number is: " + y; } Dùng toán tử trừ để trừ hai số phức // add complex numbers private void addButton_Click( object sender, System.EventArgs e ) { statusLabel.Text = x + " + " + y + " = " + ( x + y ); } // subtract complex numbers private void subtractButton_Click( object sender, System.EventArgs e ) { statusLabel.Text = x + " - " + y + " = " + ( x - y ); } 9.8 68 69 70 71 72 73 74 75 // multiply complex numbers private void multiplyButton_Click( object sender, System.EventArgs e ) { statusLabel.Text = x + " * " + y + " = " + ( x * y ); } } // end class ComplexTest OperatorOverloading.cs Dùng toán tử nhân để nhân hai số phức ComplexNumbers 9.8 OperatorOverloading.cs .. .9. 1 Lớp đối tượng - Class and Objects  Cơ sở lập trình hướng đối tượng gắn liền với đời định nghĩa lớp đối tượng  Lập trình hướng đối tượng tư tưởng lập trình liệu ( data... hour = ( ( value >= && value < 24 ) ? value : ); } 9. 1 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 } // end property Hour // property Minute... TimeTest1.cs Đối tượng this base  Không giống C++ this trỏ Trong C# Java , this đối tượng để đối tượng tham chiếu đến  Dùng đối tượng this để truy cập đến biến hàm thành viên lớp  base đối tượng

Ngày đăng: 25/03/2014, 12:21

Từ khóa liên quan

Mục lục

  • Chương 9 – Lập trình hướng đối tượng trong C#

  • 9.1. Lớp và đối tượng - Class and Objects

  • Slide 3

  • Khởi tạo đối tượng

  • Phương thức khởi tạo - Constructor

  • Slide 6

  • Slide 7

  • Slide 8

  • Slide 9

  • Slide 10

  • Slide 11

  • Đối tượng this và base

  • Slide 13

  • Slide 14

  • Slide 15

  • Bộ gom rác (Garbage Collection)

  • Slide 17

  • Slide 18

  • Các thành phần tĩnh của lớp (static Class Members)

  • Slide 20

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan