SlideShare a Scribd company logo
Introduction to C#




         Lecture 4
            FCIS
Summer training 2010, 1st year.
Contents
 
     Inheritance
 
     Calling base class constructors
 
     The protected keyword
 
     Dynamic binding; virtual and override
 
     Polymorphism and assignment compatibility
 
     All classes inherit from object
 
     The need for down casts
 
     Abstract classes
 
     Examples
Inheritance
 class Employee
 {
         int salary;
         public Employee( ) { salary = 100; }
         public void Raise( ) { salary += 50;}
 }
 class Teacher : Employee
 {
         string researchTopic;
 }
 
     In this code, the class Teacher extends the employee class. This means:
         –    Members of Employee like salary, Raise( ) are also members of
              teacher (Inheritance).
         –    Objects of type teacher can be assigned to variables of type
              employee (Polymorphism).
Inheritance
 class Test
 {
      static void Main()
      {
              Teacher t = new Teacher();
              t.Raise( ); // OK
              Employee e1 = new Employee(); // OK
              Employee e2 = new Teacher(); // OK
      }
 }
Calling base constructors
 
     It is important for the derived class's constructor
     to call the constructor of it's parent.
 
     Calling the base constructor is done via the
     base keyword.
 
     Some useful rules:
       
           If (a) The derived constructor (e.g Teacher)
           doesn't call a base constructor, and (b) The
           base has a parameterless constructor, then the
           base parameterless constructor is called
           automatically.
       
           Otherwise, the derived constructor must call the
           base constructor explicitly and give it
           parameters.
Calling base constructors - 2
 This code is correct, since Teacher's default constructor calls
   Employee's default constructor

 class Employee {
       int salary;
       public Employee( ) { salary = 100; }
       public void Raise( ) { salary += 50;}
 }
 class Teacher : Employee {
       string researchTopic;
 }
Calling base constructors - 3
 This code is also correct, since Teacher's Employee's default
   constructor is still called.
 
     class Employee {
        int salary;
        public Employee( ) { salary = 100; }
        public void Raise( ) { salary += 50;}
 }
 class Teacher : Employee {
        string researchTopic;
        public Teacher() { }
 }
Calling base constructors - 4
 But this code is incorrect, since the compiler cannot know what
   parameters to give to Employee's only constructor!
 
     class Employee {
        int salary;
        public Employee(int s) { salary = s; }
        public void Raise( ) { salary += 50;}
 }
 class Teacher : Employee {
        string researchTopic;
        public Teacher() { } // ???
 }
Calling base constructors - 4
 Now the code is correct, since all of Teacher's constructors give
   the required parameters to the base class's constructors.
 
     class Employee {
        int salary;
        public Employee(int s) { salary = s; }
        public void Raise( ) { salary += 50;}
 }
 class Teacher : Employee {
        string researchTopic;
        public Teacher() : base(100) { } // OK
        public Teacher(int _salary): base(_salary) {} // OK
 }
Protected - 1
class Employee
{
    int salary;
    public Employee( ) { salary = 100; }
    public void Raise( ) { salary += 50;}
}
class Teacher : Employee
{
    string researchTopic;
    public Teacher( )
    {
        salary = 500; // WRONG! 'salary' is private
    }
}
Protected - 2
class Employee
{
    protected int salary;
    public Employee( ) { salary = 100; }
    public void Raise( ) { salary += 50;}
}
class Teacher : Employee
{
    string researchTopic;
    public Teacher( )
    {
        salary = 500; // OK! 'salary' is protected
    }
}
Overriding
 
     A class like Teacher inherits all data members
     and methods from it's parent class.
 
     But what if some of Teacher's behavior is
     different from employee?
 
     For example, what if Raise( ) should increment
     the salary by a different amount (say 51 instead
     of 50?).
 
     In this case the derived class can override the
     method from its parent class.
 
     But the parent class must allow overriding of
     this method by making it virtual.
Overriding
     class Employee {
        int salary;
        public Employee() { salary = 100; }
        public virtual void Raise( ) { salary += 50;}
 }
 class Teacher : Employee {
        string researchTopic;
        public Teacher()   { }
        public override void Raise( ) { salary += 51; }
 }
Dynamic binding
     class Employee {
         int salary;
         public Employee() { salary = 100; }
         public virtual void Raise( ) { salary += 50;}
 }
 class Teacher : Employee {
         string researchTopic;
         public Teacher()       { }
         public override void Raise( ) { salary += 51; }
 }
 class Test {
         static void Main( ) {
                  Employee e = new Teacher( );
                  e.Raise( );
                  } }
 
     Is e.salary now equal to 150 or 151?
Object...
 
     All classes inherit from object. So an instance
     of any class can be assigned to a variable of
     type object, stored in an array of objects,
     passed to functions that take objects....etc
 
     Also, object includes functions like ToString( ),
     which (a) Can be overriden and (b) Are used
     by standard .net code like Console.WriteLine
     and list boxes.
 
     What about value types (which are not
     classes)? When you assign them to objects
     they are first copied into an object with a
     reference. This is called boxing.
Downcasts
 Employee e1, e2;
 Teacher t1, t2, t3;
 e1 = new Employee( );               // OK, same type
 Teacher t1 = new Teacher( );
 e1 = t1;                           // OK, 'Teacher' is a
                                    // subtype of 'Employee'
 Teacher t2 = e2;                   // WRONG!
 Teacher t3 = (Teacher) e2;         // OK for the compiler
      
            The last line is a downcast. It means "assume e2 is really a
            reference to a 'Teacher' object"
      
            There will be a runtime check that this is the case, and an
            exception will be thrown if e2 isn't the correct type. Otherwise
            the program will go on normally.
      
            Downcasts are sometimes needed, but are usually a sign of
            bad design; use polymorphism instead.
Abstract classes
class Shape {
      public virtual double GetArea() { ... }
}
                                                      ‫ماذا نضع‬
class Square : Shape {                                 ‫هنا؟؟؟‬
    double side;
    public Square(double s) { side = s;}
    public override double GetArea() { return side*side;}
}
class Circle : Shape {
    double radius;
    public Circle(double r) { radius = r;}
    public override double GetArea()
               { return Math.PI * radius*radius;}
}
Abstract classes
abstract class Shape {
      public abstract double GetArea();
}
class Square : Shape {
    double side;
    public Square(double s) { side = s;}
    public override double GetArea() { return side*side;}
}
class Circle : Shape {
    double radius;
    public Circle(double r) { radius = r;}
    public override double GetArea()
               { return Math.PI * radius*radius;}
}
Abstract classes

    Abstract classes represent common concepts
    between many concrete classes.

    A class that has one or more abstract functions must
    also be declared abstract.

    You cannot create instances of abstract classes (but
    you're free to create references whose types are
    abstract classes).

    If a class inherits from an abstract class, it can
    become concrete by overriding all the abstract
    methods with real methods. Now it can be
    instantiated.
Extra: A simple dialog box...
To end the session, we'll show how to create a simple
    dialog box that reads a name from the user...
Creating the dialog box...




                              Value       Property       Object
btnOk   btnCancel             btnOk       AcceptButton   Form
                              btnCancel   CancelButton   Form
                    txtName   OK          DialogResult   btnOk
                              Cancel      DialogResult   btnCancel
Creating the dialog box...
In Form2:
public string GetName( )
{
     return txtName.Text;
}
Using a dialog box...
In Form1

        void btnGetName_Click(object sender, EventArgs e)
{
    Form2 f = new Form2();
    DialogResult r = f.ShowDialog( ); // Show modal
    if(r == DialogResult.OK)
    {
        string name = f.GetName( );
        lblResult.Text = f;
    }
}
Ad

More Related Content

What's hot (20)

C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
FALLEE31188
 
Introduction to c ++ part -2
Introduction to c ++   part -2Introduction to c ++   part -2
Introduction to c ++ part -2
baabtra.com - No. 1 supplier of quality freshers
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
manish kumar
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
Thooyavan Venkatachalam
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in java
Raja Sekhar
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
manish kumar
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
Intro C# Book
 
Templates
TemplatesTemplates
Templates
Pranali Chaudhari
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)
Majid Saeed
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
Intro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
Intro C# Book
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - Abstraction
Michael Heron
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
KALAISELVI P
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
Intro C# Book
 
Op ps
Op psOp ps
Op ps
Shehzad Rizwan
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
Pranali Chaudhari
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
BG Java EE Course
 
C sharp chap5
C sharp chap5C sharp chap5
C sharp chap5
Mukesh Tekwani
 
Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructors
Pranali Chaudhari
 
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part III
Ajit Nayak
 

Viewers also liked (7)

Erlang session1
Erlang session1Erlang session1
Erlang session1
mohamedsamyali
 
Presentation skills for Graduation projects
Presentation skills for Graduation projectsPresentation skills for Graduation projects
Presentation skills for Graduation projects
mohamedsamyali
 
Computational thinking in Egypt
Computational thinking in EgyptComputational thinking in Egypt
Computational thinking in Egypt
mohamedsamyali
 
Erlang session2
Erlang session2Erlang session2
Erlang session2
mohamedsamyali
 
Smalltalk, the dynamic language
Smalltalk, the dynamic languageSmalltalk, the dynamic language
Smalltalk, the dynamic language
mohamedsamyali
 
Themes for graduation projects 2010
Themes for graduation projects   2010Themes for graduation projects   2010
Themes for graduation projects 2010
mohamedsamyali
 
Presentation skills for Graduation projects
Presentation skills for Graduation projectsPresentation skills for Graduation projects
Presentation skills for Graduation projects
mohamedsamyali
 
Computational thinking in Egypt
Computational thinking in EgyptComputational thinking in Egypt
Computational thinking in Egypt
mohamedsamyali
 
Smalltalk, the dynamic language
Smalltalk, the dynamic languageSmalltalk, the dynamic language
Smalltalk, the dynamic language
mohamedsamyali
 
Themes for graduation projects 2010
Themes for graduation projects   2010Themes for graduation projects   2010
Themes for graduation projects 2010
mohamedsamyali
 
Ad

Similar to C# Summer course - Lecture 4 (20)

Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
Ramrao Desai
 
38-object-concepts.ppt
38-object-concepts.ppt38-object-concepts.ppt
38-object-concepts.ppt
Ravi Kumar
 
38 object-concepts (1)
38 object-concepts (1)38 object-concepts (1)
38 object-concepts (1)
Shambhavi Vats
 
oops -concepts
oops -conceptsoops -concepts
oops -concepts
sinhacp
 
38 object-concepts
38 object-concepts38 object-concepts
38 object-concepts
raahulwasule
 
Basic object oriented concepts (1)
Basic object oriented concepts (1)Basic object oriented concepts (1)
Basic object oriented concepts (1)
Infocampus Logics Pvt.Ltd.
 
OOPS
OOPSOOPS
OOPS
infotechspecial
 
A457405934_21789_26_2018_Inheritance.ppt
A457405934_21789_26_2018_Inheritance.pptA457405934_21789_26_2018_Inheritance.ppt
A457405934_21789_26_2018_Inheritance.ppt
RithwikRanjan
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
Mahmoud Alfarra
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
Epsiba1
 
Assignment 7
Assignment 7Assignment 7
Assignment 7
IIUM
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppt
henokmetaferia1
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
MODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptxMODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptx
VeerannaKotagi1
 
L03 Software Design
L03 Software DesignL03 Software Design
L03 Software Design
Ólafur Andri Ragnarsson
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
Tareq Hasan
 
05 Object Oriented Concept Presentation.pptx
05 Object Oriented Concept Presentation.pptx05 Object Oriented Concept Presentation.pptx
05 Object Oriented Concept Presentation.pptx
ToranSahu18
 
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptxObject Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
RashidFaridChishti
 
Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2
Kamlesh Singh
 
C++ Presen. tation.pptx
C++ Presen.                   tation.pptxC++ Presen.                   tation.pptx
C++ Presen. tation.pptx
mohitsinha7739289047
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
Ramrao Desai
 
38-object-concepts.ppt
38-object-concepts.ppt38-object-concepts.ppt
38-object-concepts.ppt
Ravi Kumar
 
38 object-concepts (1)
38 object-concepts (1)38 object-concepts (1)
38 object-concepts (1)
Shambhavi Vats
 
oops -concepts
oops -conceptsoops -concepts
oops -concepts
sinhacp
 
38 object-concepts
38 object-concepts38 object-concepts
38 object-concepts
raahulwasule
 
A457405934_21789_26_2018_Inheritance.ppt
A457405934_21789_26_2018_Inheritance.pptA457405934_21789_26_2018_Inheritance.ppt
A457405934_21789_26_2018_Inheritance.ppt
RithwikRanjan
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
Epsiba1
 
Assignment 7
Assignment 7Assignment 7
Assignment 7
IIUM
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppt
henokmetaferia1
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
MODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptxMODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptx
VeerannaKotagi1
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
Tareq Hasan
 
05 Object Oriented Concept Presentation.pptx
05 Object Oriented Concept Presentation.pptx05 Object Oriented Concept Presentation.pptx
05 Object Oriented Concept Presentation.pptx
ToranSahu18
 
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptxObject Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
RashidFaridChishti
 
Ad

Recently uploaded (20)

Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 

C# Summer course - Lecture 4

  • 1. Introduction to C# Lecture 4 FCIS Summer training 2010, 1st year.
  • 2. Contents  Inheritance  Calling base class constructors  The protected keyword  Dynamic binding; virtual and override  Polymorphism and assignment compatibility  All classes inherit from object  The need for down casts  Abstract classes  Examples
  • 3. Inheritance class Employee { int salary; public Employee( ) { salary = 100; } public void Raise( ) { salary += 50;} } class Teacher : Employee { string researchTopic; }  In this code, the class Teacher extends the employee class. This means: – Members of Employee like salary, Raise( ) are also members of teacher (Inheritance). – Objects of type teacher can be assigned to variables of type employee (Polymorphism).
  • 4. Inheritance class Test { static void Main() { Teacher t = new Teacher(); t.Raise( ); // OK Employee e1 = new Employee(); // OK Employee e2 = new Teacher(); // OK } }
  • 5. Calling base constructors  It is important for the derived class's constructor to call the constructor of it's parent.  Calling the base constructor is done via the base keyword.  Some useful rules:  If (a) The derived constructor (e.g Teacher) doesn't call a base constructor, and (b) The base has a parameterless constructor, then the base parameterless constructor is called automatically.  Otherwise, the derived constructor must call the base constructor explicitly and give it parameters.
  • 6. Calling base constructors - 2 This code is correct, since Teacher's default constructor calls Employee's default constructor class Employee { int salary; public Employee( ) { salary = 100; } public void Raise( ) { salary += 50;} } class Teacher : Employee { string researchTopic; }
  • 7. Calling base constructors - 3 This code is also correct, since Teacher's Employee's default constructor is still called.  class Employee { int salary; public Employee( ) { salary = 100; } public void Raise( ) { salary += 50;} } class Teacher : Employee { string researchTopic; public Teacher() { } }
  • 8. Calling base constructors - 4 But this code is incorrect, since the compiler cannot know what parameters to give to Employee's only constructor!  class Employee { int salary; public Employee(int s) { salary = s; } public void Raise( ) { salary += 50;} } class Teacher : Employee { string researchTopic; public Teacher() { } // ??? }
  • 9. Calling base constructors - 4 Now the code is correct, since all of Teacher's constructors give the required parameters to the base class's constructors.  class Employee { int salary; public Employee(int s) { salary = s; } public void Raise( ) { salary += 50;} } class Teacher : Employee { string researchTopic; public Teacher() : base(100) { } // OK public Teacher(int _salary): base(_salary) {} // OK }
  • 10. Protected - 1 class Employee { int salary; public Employee( ) { salary = 100; } public void Raise( ) { salary += 50;} } class Teacher : Employee { string researchTopic; public Teacher( ) { salary = 500; // WRONG! 'salary' is private } }
  • 11. Protected - 2 class Employee { protected int salary; public Employee( ) { salary = 100; } public void Raise( ) { salary += 50;} } class Teacher : Employee { string researchTopic; public Teacher( ) { salary = 500; // OK! 'salary' is protected } }
  • 12. Overriding  A class like Teacher inherits all data members and methods from it's parent class.  But what if some of Teacher's behavior is different from employee?  For example, what if Raise( ) should increment the salary by a different amount (say 51 instead of 50?).  In this case the derived class can override the method from its parent class.  But the parent class must allow overriding of this method by making it virtual.
  • 13. Overriding class Employee { int salary; public Employee() { salary = 100; } public virtual void Raise( ) { salary += 50;} } class Teacher : Employee { string researchTopic; public Teacher() { } public override void Raise( ) { salary += 51; } }
  • 14. Dynamic binding class Employee { int salary; public Employee() { salary = 100; } public virtual void Raise( ) { salary += 50;} } class Teacher : Employee { string researchTopic; public Teacher() { } public override void Raise( ) { salary += 51; } } class Test { static void Main( ) { Employee e = new Teacher( ); e.Raise( ); } }  Is e.salary now equal to 150 or 151?
  • 15. Object...  All classes inherit from object. So an instance of any class can be assigned to a variable of type object, stored in an array of objects, passed to functions that take objects....etc  Also, object includes functions like ToString( ), which (a) Can be overriden and (b) Are used by standard .net code like Console.WriteLine and list boxes.  What about value types (which are not classes)? When you assign them to objects they are first copied into an object with a reference. This is called boxing.
  • 16. Downcasts Employee e1, e2; Teacher t1, t2, t3; e1 = new Employee( ); // OK, same type Teacher t1 = new Teacher( ); e1 = t1; // OK, 'Teacher' is a // subtype of 'Employee' Teacher t2 = e2; // WRONG! Teacher t3 = (Teacher) e2; // OK for the compiler  The last line is a downcast. It means "assume e2 is really a reference to a 'Teacher' object"  There will be a runtime check that this is the case, and an exception will be thrown if e2 isn't the correct type. Otherwise the program will go on normally.  Downcasts are sometimes needed, but are usually a sign of bad design; use polymorphism instead.
  • 17. Abstract classes class Shape { public virtual double GetArea() { ... } } ‫ماذا نضع‬ class Square : Shape { ‫هنا؟؟؟‬ double side; public Square(double s) { side = s;} public override double GetArea() { return side*side;} } class Circle : Shape { double radius; public Circle(double r) { radius = r;} public override double GetArea() { return Math.PI * radius*radius;} }
  • 18. Abstract classes abstract class Shape { public abstract double GetArea(); } class Square : Shape { double side; public Square(double s) { side = s;} public override double GetArea() { return side*side;} } class Circle : Shape { double radius; public Circle(double r) { radius = r;} public override double GetArea() { return Math.PI * radius*radius;} }
  • 19. Abstract classes  Abstract classes represent common concepts between many concrete classes.  A class that has one or more abstract functions must also be declared abstract.  You cannot create instances of abstract classes (but you're free to create references whose types are abstract classes).  If a class inherits from an abstract class, it can become concrete by overriding all the abstract methods with real methods. Now it can be instantiated.
  • 20. Extra: A simple dialog box... To end the session, we'll show how to create a simple dialog box that reads a name from the user...
  • 21. Creating the dialog box... Value Property Object btnOk btnCancel btnOk AcceptButton Form btnCancel CancelButton Form txtName OK DialogResult btnOk Cancel DialogResult btnCancel
  • 22. Creating the dialog box... In Form2: public string GetName( ) { return txtName.Text; }
  • 23. Using a dialog box... In Form1  void btnGetName_Click(object sender, EventArgs e) { Form2 f = new Form2(); DialogResult r = f.ShowDialog( ); // Show modal if(r == DialogResult.OK) { string name = f.GetName( ); lblResult.Text = f; } }