TÀI LIỆU ĐẠI HỌC - godautre PPLT-Chuong 4 tài liệu, giáo án, bài giảng , luận văn, luận án, đồ án, bài tập lớn về tất cả...
Trang 2Tìm hiểu các phương pháp OOP trong một vài ngôn ngữ lập trình phổ biến hiện nay
• VB.NET
Trang 34.1
Lập trình hướng đối tượng
trong C#
Trang 5Kiểu Ý nghĩa
public Như C++.
private Như C++
protecte
d Được truy xuất bởi các thành phần cùng lớp hoặc từ các lớp dẫn xuất.
internal Các thành phần trong lớp A được gán là internal có thể truy
xuất được các method của bất kỳ lớp nào trong assembly của A.
Trang 6Các đối số của method
void MyMethod (int firstParam, Button secondParam) { // }
#region Using directives
}
Trang 7Tạo các đối tượng
// public accessor methods
public void DisplayCurrentTime( )
static void Main( ) {
System.DateTime currentTime = System.DateTime.Now; Time t = new Time( currentTime ); t.DisplayCurrentTime( );
} } }
Output:
03/11/2010 16:21:40
Trang 8Các kiểu cơ sở và giá trị mặc định của chúng
Trang 9Khởi tạo giá trị
// private member variables
private int Year;
private int Month;
private int Date;
private int Hour;
private int Minute;
private int Second = 30; // initializer
// public accessor methods
public void DisplayCurrentTime( )
{
System.DateTime now = System.DateTime.Now;
System.Console.WriteLine( "\nDebug\t: {0}/{1}/{2} {3}:{4}:{5}",
now.Month, now.Day, now.Year, now.Hour, now.Minute, now.Second );
System.Console.WriteLine( "Time\t: {0}/{1}/{2} {3}:{4}:{5}", Month, Date, Year, Hour, Minute, Second );
}
Trang 10public Time( int Year, int Month, int Date,
int Hour, int Minute )
Time t = new Time( currentTime );
t.DisplayCurrentTime( );
Time t2 = new Time( 2010, 03, 18, 11, 45 ); t2.DisplayCurrentTime( );
} } }
Output:
Debug : 03/11/2010 7:52:54 Time : 03/11/2010 7:52:54 Debug : 03/11/2010 7:52:54 Time : 03/18/2010 11:45:30
Trang 11Từ khoá this
• this được sử dụng để tham chiếu đến thực thể hiện tại của đối tượng:
public void SomeMethod (int hour ) { this.hour = hour ;
}
• this được sử dụng đây thực thể hiện tại sang một method khác:
private int hour ;
class myClass {
public void Foo(OtherClass otherObject ) { otherObject.Bar ( this );
} }
• this được sử dụng với các chỉ số (xem sau)
• this được sử dụng để tham chiếu đến lời gọi một cấu tử overload từ một thành
phần khác
class myClass {
số là số nguyên.
Trang 120 cats adopted
1 cats adopted
2 cats adopted
Trang 13Hũy các đối tượng
• Hũy tử trong C#
Định nghĩa một hũy tử trong C#
kiểu như:
~MyClass() {
// làm gì đó ở đây }
Khi viết như trên, C# sẽ
dịch nó thành:
protected override void Finalize() {
try { //làm gì đó ở đây.
} finally {
base.Finalize( );
} }
Trang 14• Dispose
• Để đóng và loại bỏ đối tượng một cách nhanh chóng, có thể thực hiện giao
tiếp IDisposable Giao tiếp IDisposable yêu cầu định nghĩa một method có tên là Dispose()
• Cách này kiểu như nói “Không đợi cho cấu tử được gọi, hãy thực hiện nó ngay bây giờ”
• Khi thiết kế một method Dispose(), ta phải dừng việc việc gọi cấu tử của đối tượng Để thực hiện điều này, gọi method static GC.SuppressFinalize( ) với việc truyền con trỏ đến đối tượng hiện thời (this)
• Cấu tử cũng có thể gọi method Dispose( ).
Trang 15using System;
class Testing : IDisposable
{
bool is_disposed = false;
protected virtual void Dispose(bool disposing)
Trang 17• Sử dụng lệnh using
Để người sử dụng dễ hơn
trong việc loại bỏ các đối
tượng, C# cung cấp lệnh
using trong đó nó đảm bảo
hàm Dispose() sẽ được gọi
class Tester {
public static void Main( ) {
using ( Font Font1 = new Font( "Arial", 10.0f ) ) {
// sử dụng Font1 } // C# sẽ gọi Dispose cho Font1
Font Font2 = new Font( "Courier", 12.0f );
using ( Font2 ) {
// sử dụng Font2
} // C# sẽ gọi Dispose cho Font2
} } }
Trang 18// private member variables
private int Year;
private int Month;
private int Date;
private int Hour;
private int Minute;
private int Second;
public void DisplayCurrentTime( )
{
System.Console.WriteLine( "{0}/{1}/{2} {3}:{4}:
{5}", Month, Date, Year, Hour, Minute, Second );
}
Trang 19public int GetHour( )
Time t = new Time( currentTime );
t.DisplayCurrentTime( );
int theHour = 0;
int theMinute = 0;
int theSecond = 0;
t.GetTime( theHour, theMinute, theSecond );
System.Console.WriteLine( "Current time: {0}:{1}: {2}", theHour, theMinute, theSecond );
} } }
Output:
03/11/2010 13:41:18
Current time: 0:0:0
Trang 20• Sử dụng các khai báo in , out và ref cho tham số
ref: được sử dụng như làm tham biến
out: các tham số được sử dụng chỉ để trả lại thông tin từ hàm
// private member variables
private int Year;
private int Month;
private int Date;
private int Hour;
private int Minute;
private int Second;
// public accessor methods
public void DisplayCurrentTime( )
Trang 21public void SetTime( int hr, out int min, ref int sec )
Hour = hr; // set to value passed in
// pass the minute and second back out
Time t = new Time( currentTime );
theMinute, theSecond );
} } } Output:03/11/2010 14:6:24
the Minute is now: 6 and 24 seconds the Minute is now: 7 and 0 seconds
Trang 22// private member variables
private int Year;
private int Month;
private int Date;
private int Hour;
private int Minute;
private int Second;
// public accessor methods
public void DisplayCurrentTime( )
{ Year = dt.Year;
Trang 23public class Tester
{
static void Main( )
{
System.DateTime currentTime = System.DateTime.Now;
Time t = new Time( currentTime );
Trang 24• Biến đổi kiểu kết quả trả lại trong các hàm overload
… namespace VaryingReturnType {
public class Tester {
private int Triple( int val ) { return 3 * val; }
private long Triple( long val ) { return 3 * val; }
public void Test( ) { int x = 5;
Tester t = new Tester( );
t.Test( );
} } }
Trang 25Lấy dữ liệu với các thuộc tính
Cú pháp:
public type propertier_name
{ get
Trang 26// private member variables
private int year;
private int month;
private int date;
private int hour;
private int minute;
private int second;
// public accessor methods
public void DisplayCurrentTime( )
{ get
{ return hour;
} set
{ hour = value;
} } }
public class Tester {
static void Main( ) { System.DateTime currentTime = System.DateTime.Now;
Time t = new Time( currentTime );
t.DisplayCurrentTime( );
int theHour = t Hour ; System.Console.WriteLine( "\nRetrieved the hour: {0}\n", theHour );
Trang 27Sửa đổi thuộc tính truy xuất:
Có thể đặt trước get, set các tính chất protected, internal, private
để quy định cách thức truy xuất:
Trang 28Kế thừa (Inheritance)
• Trong C#, để tạo một lớp dẫn xuất, sử dụng cú pháp:
public class derived_class : base_class
Ví dụ:
public class ListBox : Control
• Lớp dẫn xuất kế thừa tất cả các thành phần từ lớp
cơ sở (cả biến lẫn hàm thành phần)
Trang 29protected int top;
protected int left;
public Control( int top, int left )
{
this.top = top;
this.left = left;
}
// simulates drawing the window
public virtual void DrawWindow( )
private string listBoxContents; // new member variable
public ListBox( int top, int left, string contents ): base(top, left) // call base constructor {
listBoxContents = contents;
} // an overridden version (note keyword) because in the
// derived method we change the behavior
public override void DrawWindow( ) {
base.DrawWindow( ); // invoke the base method Console.WriteLine( "Writing string to the listbox: {0}", listBoxContents );
}
}
Trang 30public class Button : Control
// an overridden version because in the
// derived method we change the behavior
public override void DrawWindow( )
Control win = new Control( 1, 2 );
ListBox lb = new ListBox( 3, 4, "Stand alone list box" );
Button b = new Button( 5, 6 );
win.DrawWindow( );
lb.DrawWindow( );
b.DrawWindow( );
Control[] winArray = new Control[3];
winArray[0] = new Control( 1, 2 );
winArray[1] = new ListBox( 3, 4, "List box in array" ); winArray[2] = new Button( 5, 6 );
for ( int i = 0; i < 3; i++ ) {
winArray[i].DrawWindow( );
} } } }
Output:
Control: drawing Control at 1, 2
Control: drawing Control at 3, 4
Writing string to the listbox: Stand alone list box
Drawing a button at 5, 6
Control: drawing Control at 1, 2
Control: drawing Control at 3, 4
Writing string to the listbox: List box in array
Drawing a button at 5, 6
Trang 31Các lớp trừu tượng (Abstract Classes)
protected int top;
protected int left;
public Control( int top, int left )
private string listBoxContents;
public ListBox( int top, int left, string contents ):
base(top, left) { listBoxContents = contents; }
// an overridden version implementing the abstract method
public override void DrawWindow( ) {Console.WriteLine( "Writing string to the listbox: {0}", listBoxContents );
// implement the abstract method
public override void DrawWindow( ) { Console.WriteLine( "Drawing a button at {0}, {1}\n", top, left );
}
}
Trang 32public class Tester
{
static void Main( )
{
Control[] winArray = new Control[3];
winArray[0] = new ListBox( 1, 2, "First List Box" );
winArray[1] = new ListBox( 3, 4, "Second List Box" ); winArray[2] = new Button( 5, 6 );
for ( int i = 0; i < 3; i++ )
Trang 33Gốc của tất cả các lớp: Object
• Tất cả các lớp của C# đều dẫn xuất từ System.Object
• Object cung cấp một số hàm ảo mà các lớp dẫn xuất (lớp con) có thể override (xem bảng)
Equals( ) Định giá có hay không hai object là tương đương.
GetHashCode( ) Cho phép các đối tượng cho lại hàm hash để sử dụng trong tập hợp
GetType( ) Hỗ trợ việc truy xuất đến kiểu đối tượng.
ToString( ) Cung cấp một chuổi biểu diễn của đối tượng.
Finalize( ) Cleans up tài nguyên, thực hiện bởi một hũy tử.
Trang 34private int val;
public SomeClass( int someVal )
SomeClass s = new SomeClass( 7 );
Console.WriteLine( "The value of s is {0}", s.ToString( ) ); DisplayValue( s );
} } }
Output:
The value of i is: 5 The value of the object passed in is 5 The value of s is 7
The value of the object passed in is 7
Trang 35private int numerator;
private int denominator;
public Fraction( int numerator, int denominator )
}
}
Trang 36public class Tester
Trang 37Các giao tiếp (Interfaces)
• Một Interface là một sự đảm bảo cho một class, một struct sẽ chạy
Khi một class/struct thực hiện một giao tiếp, nó nói lên rằng “Tôi đảm
bảo tôi sẽ hỗ trợ các hàm, các thuộc tính, các sự kiện, các bảng mục của Interface bởi tên gọi”.
• Khi định nghĩa một Interface, phải định nghĩa các method, propertie, các indexer, và/hoặc các event mà chúng sẽ thực hiện bởi lớp chứa Interface.
•
• Interface thường được so sánh với abstract classes Một abstract
class phục vụ như là một base class cho một họ các derived classes, trong khi các interface có ý nghĩa là trộn các cây kế thừa khác.
• Khi một lớp thực hiện một interface, nó phải thực hiện tất cả các phần
mà interface (methods, properties, ); có hiệu lực, lớp nói rằng “Tôi
đồng ý thực hiện quy định được định nghĩa bởi interface này."
Trang 38• Định nghĩa và thực hiện một interface
Cú pháp:
[attributes] [access-modifier] interface interface-name[:base-list]
{interface-body}
• attributes : khai báo thuộc tính
• access_modifier : gồm public, private, protected, internal, protected internal,
• Interface : từ khoá
• interface-name : Tên của interface Nó thường (nhưng không bắt buuộc) bắt
đầu bởi chữ cái I (chẳng hạn IStorable, ICloneable, IClaudius, ).
• base-list : Danh sách các interface mà interface này mở rộng.
• interface-body : mô tả các method, các propertie phải được thực hiện bởi lớp
Trang 39void Write( object obj );
int Status { get; set; }
}
// create a class which implements the IStorable interface
public class Document : IStorable {
// store the value for the property
private int status = 0;
public Document( string s ) { Console.WriteLine( "Creating document with: {0}", s ); }
// implement the Read method
public void Read( ) { Console.WriteLine(
"Implementing the Read Method for IStorable" );
}
// implement the Write method
public void Write( object o ) { Console.WriteLine(
"Implementing the Write Method for IStorable" );
}
// implement the property
public int Status {
get { return status;
} set { status = value;
} }
}
Trang 40// Take our interface out for a spin
public class Tester
{
static void Main( )
{
// access the methods in the Document object
Document doc = new Document( "Test Document" );
Document Status: -1
Trang 41• Thực hiện nhiều hơn một interface
public class Document : IStorable, ICompressible
Trang 42Ví dụ về việc mở
rộng và liên hợp
các giao tiếp
namespace ExtendAndCombineInterface {
interface IStorable {
void Read( );
void Write( object obj );
int Status { get; set; } }
// here's the new interface
interface ICompressible
{ void Compress( );
void Decompress( );
}
// Extend the interface
interface ILoggedCompressible : ICompressible {
void Encrypt( );
void Decrypt( );
}
Trang 43public class Document : IStorableCompressible, IEncryptable
{
private int status = 0;
// the document constructor
public Document( string s )
{ Console.WriteLine( "Creating document with: {0}", s );
Trang 45public class Tester
{
static void Main( )
{ // create a document object
Document doc = new Document( "Test Document" );
// cast the document to the various interfaces
IStorable isDoc = doc as IStorable;
if ( isDoc != null )
{ isDoc.Read( );
}
else
Console.WriteLine( "IStorable not supported" );
ICompressible icDoc = doc as ICompressible;
Console.WriteLine( "Compressible not supported" );
ILoggedCompressible ilcDoc = doc as ILoggedCompressible;
Trang 46IStorableCompressible isc = doc as IStorableCompressible;
Trang 474.2
Một số vấn đề về OOP đối với
VB.NET
Trang 481 Định nghĩa class
Public Class Car
Public MaximumSpeed as Integer
Public ModelName as String
Public Sub Accelerate() ….
Có 4 cách tạo đối tượng:
1 Dim oCar as New Car
2 oCar = New Car
3 oCar = Assembly.CreateInstance("Car")
4 oCar = System.Activator.CreateInstance("Car","URIToAssembly")