Class declaration[access modifier] class [:base class, interfaces…] { // class body} Access modifier public protected internal protected internal Base class: only one class or not Inter
Trang 1CLASS, STRUCT, INTERFACE
ThS Nguyễn Hà Giang
Trang 3Class declaration
[access modifier] class <class_name> [:base class, interfaces…]
{
// class body}
Access modifier
public
protected
internal protected internal
Base class: only one class or not
Interface: implement some interfaces
Trang 4Access modifier public
No base class
Default derive from
object (System.Object)
Trang 5Field, const, readonly
Nested type
Trang 6• Called when create object
• Class has default constructor which no
parameter
• Class has multiple constructor (overloading
constructor)
Trang 7• Input parameter is another object
• Create new object like input object
• Other constructors
• One or more parameter
• Create new object with some information
Trang 8{
// data memberstring name;
// function member
…}
public Student()
{
name = “Ha Giang";
public Student(Student st){
name = st.name; public Student(string sname)
Trang 9• The private constructor prevents the class from being created
class Student {
//
private Student() {
} } class Program {
static void Main(string[] args) {
Student s = new Student();
}
Trang 10• Call one constructor from another constructor
• Usage
• base(parameter): call constructor of base class
• this(parameter): call a constructor in the current class
<constructor of class A> : base (list of parameter)
Trang 11class Person {
protected string name;
protected int year;
public Person(string name, int year) { this.name = name;
this.year = year;
} } class Student : Person { float mark;
public Student(string name, int year, float mark) : base(name, year)
{ this.mark = mark;
}
Call base constructor
Trang 12class Student {
{
Call constructor
Trang 13• Features of destructor
• A class can have one destructor only
• Destructor cannot be inherited or overloaded
• Destructor are invoked automatically
• Destructor can not have modifiers or parameters
class Student {
//…
~ Student() // destructor {
//Code for cleanup resources
Trang 16number++; //increment 1}
public void Show() {Console.WriteLine("{0} ",name);
}public static int NumberOfInstance() {return number; // return number of objects
Trang 17Student s1 = new Student("Ha Giang");
Student s2 = new Student("Ngoc Thao");
Student s3 = new Student("Ha Nam");
s1.Show();
int num = Student.NumberOfInstance();
Console.WriteLine("Number of objects: {0}", num);
Console.ReadLine();
}}
Invoked by instance of class
Called directly from the class
Trang 19a = b;
b = temp;
} public void Swap(ref float a, ref float b) { float temp = a;
Trang 20Virtual Method
Employee
SaleEmployee
Trang 21public void CalculatePay() {
Console.WriteLine("SaleEmployee.CalculatePay");
}
SaleEmployee s = new SaleEmployee();
Trang 22public override void CalculatePay() {
Console.WriteLine("SaleEmployee.CalculatePay");
}
SaleEmployee s = new SaleEmployee();
e.CalculatePay();
s.CalculatePay();
Polymorphism!
Trang 24• Properties as “smart” fields
[modifers] <type> <property-name>
{
[ set { <accessor-body> } ] [ get { <accessor-body >} ] }
[modifers] <type> <property-name>
{
[modifers] <type> <property-name>
{
Trang 25class Employee {
// fields private string name;
private float salary;
// properties public string NAME { get {
return name;
} set { name = value;
} } public float SALARY { get {
return salary;
} }
Read write property
Read only property
Trang 26• How to use properties
… Employee e = new Employee();
e.NAME = "Nguyen Ha Giang";
float salary = e.SALARY;
…
Call set property of NAME
Call get property of
SALARY
Trang 27• Advanced use of properties
• Provide a level of abstraction to clients so that the client doesn’t need to know if an accessor exists for the member being accessed
• Provide a generic means of accessing class member
• Enable class to guarantee that any additional processing can be done when a particular field is modified or accessed.
Trang 28• Treating objects like arrays by using indexers
• Indexers are similar to properties except that
their accessors take parameters.
[modifier] < data_type_of_object > this
[< data_type_for _index > index_name]
{
Trang 29class MyList {
private ArrayList item = new ArrayList();
public string this[int index]
{set{
if (index >= 0 && index < item.Count){
item[index] = value;
}else if (index == item.Count)item.Add(value);
elsethrow new InvalidOperationException("Index out of range");
Trang 30class MyList
{private ArrayList item = new ArrayList();
public string this[int index]
{
…get{
if (index >= 0 && index < item.Count)return (string) item[index];
elsethrow new InvalidOperationException("Index out of range");
Trang 31static void Main(string[] args){
MyList list = new MyList();
list[0] = "Nguyen Ha Giang";
list[1] = "Nguyen Ha Nam";
list[2] = “Ha Mỹ Tiên";
Console.WriteLine("{0} - {1} - {2}", list[0], list[1], list[2]);
Console.ReadLine();
}
?
Trang 32Down cast – Up cast
public class Shape
{ protected int x;
protected int y;
public Shape() { } public Shape(int x, int y) { this.x = x; this.y = y; }
public virtual void Draw() {
Console.WriteLine("Drawing a shape at {0},{1}", x, y);
Trang 33Down cast – Up cast
public class Square : Shape
{
public Square() { } public Square(int x, int y) : base(x, y) { } public override void Draw()
{ Console.WriteLine("Drawing a square at {0},{1}", x, y);
} }
public class Circle : Shape
{
public Circle() { } public Circle(int x, int y) : base(x, y) { } public override void Draw()
{ Console.WriteLine("Drawing a circle at {0},{1}", x, y);
Trang 34Down cast – Up cast
Trang 35Down cast – Up cast
static void Main(string[] args)
Trang 36Down cast – Up cast
static void Main(string[] args)
{
Shape[] shapes = new Shape[3];
shapes[0] = new Shape(10, 10);
shapes[1] = new Circle(20, 20);
shapes[2] = new Square(30, 30);
foreach (Shape s in shapes) s.Draw();
Console.ReadLine();
Drawing a shape at 10,10 Drawing a circle at 20,20
Trang 37Up cast – Down cast
Shape s = new Circle(100, 100);
Cast Circle to the type ShapeAll methods and properties of Shape to exist in CircleUp-casting: moving up the object hierarchy to the type Shape, casting our object upward to its parent type
Trang 38Up cast – Down cast
public class Circle : Shape
{
public Circle() { } public Circle(int x, int y) : base(x, y) { } public override void Draw()
{ Console.WriteLine("Drawing a circle at {0},{1}", x, y);
} public void FillCircle () {
Console.WriteLine(“Filling circle at {0},{1}”,x, y);
Trang 39Up cast – Down cast
Trang 40Up cast – Down cast
Circle c;
c = (Circle) sh;
c.FillCircle();
Trang 41Up cast – Down cast
• Using the “is” keyword before down cast to test type
foreach (Shape shape in shapes) {
shape.Draw();
if (shape is Circle) ((Circle)shape).FillCircle();
if (shape is Square) ((Square)shape).FillSquare();
}
Trang 42Up cast – Down cast
foreach (Shape shape in shapes) {
Trang 43Abstract class
• An abstract class cannot be instantiated
• Provide a common definition of a base class that multiple derived classes can share
• Abstract classes may also define abstract
methods
• Abstract methods have no implementation
Trang 44Abstract class
{
protected string name;
protected float rate;
public Employee(string name, float rate) {
this.name = name;
this.rate = rate;
} public virtual float CalculateCharge(float hour) {
return (hour * rate);
Trang 45Abstract class
class Manager : Employee {
public Manager(string name, float rate) : base(name, rate) { }
public override float CalculateCharge(float hour) {
if (hour < 1.0f) hour = 1.0f; //minimum charge return hour * rate;
} public override string TypeName() { return "Manager"; } }
class Staff : Employee {
public Staff(string name, float rate) : base(name, rate) { } public override string TypeName() { return "Staff"; }
Trang 46Abstract class
static void Main(string[] args) {
Employee[] emp = new Employee[2];
emp[0] = new Manager("Ha Nam", 3.0f);
emp[1] = new Staff("Ha Giang", 1.0f);
Console.WriteLine("{0} charge {1}", emp[0].CalculateCharge(40), emp[0].TypeName());
Console.WriteLine("{0} charge {1}", emp[1].CalculateCharge(45), emp[1].TypeName());
Trang 47• It also enables certain run-time optimizations.
• Structs are implicitly sealed; therefore, they
cannot be inherited.
Trang 48Sealed class
namespace HaGiang{
sealed class Student {
Trang 49support inheritance no inheritance for
structs used for complex and
large set data
are simple to use
Trang 50struct Point{
{Point p;
p.x = p1.x + p2.x;
p.y = p1.y + p2.y;
Trang 51class Program{
public static void Main(){
Point p1 = new Point(5, 5); // using new keywordPoint p2; // another way
p2.x = 8; // assign a value for xp2.y = 8; // assign a value for yPoint p3 = p1 + p2; // add
Console.WriteLine("P1.x = {0}, P1.y = {1}", p1.x, p1.y);
Console.WriteLine("P2.x = {0}, P2.y = {1}", p2.x, p2.y);
Console.WriteLine("P3.x = {0}, P3.y = {1}", p3.x, p3.y);
Console.ReadLine();
}
Trang 52• Interface defines a contract
• Any class that implement an interface must define each and every member of that interface
• An interface is a reference type object with no
implementation
• Interface contains
• Methods, properties, indexers and events
• Using when disparate classes need to share
Trang 53interface IDrawing {
int X { get;
set;
} int Y { get;
set;
} void Draw(); //method for drawing }
Trang 54}public int Y {get { return y; }set { y = value;}
}
Trang 55• Provide a method of comparing two objects of a particular type.
• Ex: Student, Person, Car, Employee…
• Problem & solution:
• if you have an array of Student objects, you call the Sort method on that array, IComparable provides the comparison of objects during the sort.
Trang 56class Employee: IComparable {
//data member private string name;
private float salary;
// constructor public Employee(string name, float salary) {
this.name = name;
this.salary = salary;
} // method public void Show()
Trang 57… /// <summary>
/// implement CompareTo method from IComparable /// </summary>
/// <param name="obj">the second employee object for comparing</param>
/// <returns>
/// -1: if this object is come first /// 0: if this and second one are equal /// 1: if the second object is come first /// </returns>
public int CompareTo(object obj){
// compare to field nameEmployee e2 = (Employee)obj;
return this.name.CompareTo(e2.name);
}
Trang 58static void Main(string[] args) {
Employee[] emps = new Employee[3];
emps[0] = new Employee("Nam", 100);
emps[1] = new Employee("Binh", 400);
emps[2] = new Employee("Hung", 200);
foreach (Employee e in emps) e.Show();
// after sorting by name Array.Sort(emps);
foreach (Employee e in emps)
Trang 60IComparer