SlideShare una empresa de Scribd logo
1 de 48
Object Oriented Programming




           Why?
Procedural Approach

 Focus is on procedures
 All data is shared: no protection
 More difficult to modify
 Hard to manage complexity
OOPs Concepts


 It is a system modeling technique in which the system is
  design with using discrete objects.

The basic components of OOP’s are:-

 Class:- It is written description of objects, It is collection of
  properties and behaviors.
 Object:- They are real time things, something that
  exist, something that is used.
  Object is anything that is identifiable as a single material
  item.
Objects and Classes


 Classes reflect concepts, objects reflect
 instances that embody those concepts.

    object               class              girl




        Jodie    Daria   Jane    Brittany
Objects and Classes


 Class                        Object
    Visible in source code       Own copy of data
    The code is not              Active in running
     duplicated                    program
                                  Occupies memory
                                  Has the set of operations
                                   given in the class
Objects and Classes


 A class captures the common properties of
  the objects instantiated from it
 A class characterizes the common behavior of
  all the objects that are its instances
Instantiation

 An Object is instantiated from a Class




       MyClass1 ob;
       ob = new MyClass1;

 Objects without memory is called Object and
 Objects with memory is called Instance.

 Note:- Only instance of classes are used in the program.
Different Types of Variables:

 Class Variable: They are Static members and accessed with the
  name of class rather than reference to objects. (by using “Static”
  keyword)



 Instance Variable: They are used with instance not through
                             class.
 Local Variable: They are defined within a method
Examples of Variables

Class Employee
{
  private static int C_vbl;
  private int I_vbl;
Public void Class_Method()
  {
      int L_variable=100;
  }
}
Implementation of Static/Class Variable

   class Test
   {
   public int rollNo;
   public int mathsMarks;
   public static int totalMathMarks;
   }
   class TestDemo
   {
   public static void main()
   {
   Test ob = new Test();
   ob.rollNo = 1;
   ob.mathsMarks = 40;
   ob.rollNo = 2;
   ob.mathsMarks = 43;
   Test.totalMathsMarks = ob.mathsMarks + ob.mathsMarks;
   }
   }
Properties of OOP‟s

Key Concepts of Object Orientation
 Encapsulation
 Abstraction
 Inheritance
 Polymorphism
Data Encapsulation


How the object *should* be used.
It allow you to hide internal state of objects and abstract access to it
though type members such as
Access Modifiers, methods, properties, and indexers.
Access Modifiers
  C# provides us following 5 access modifiers:

 Private:       Used within the same class

 Protected: Can be used by Inheritance class

 Public:        Can be excess by anyone

 Internal:      Can be used within the same project

 Protected Internal: Can be used by Inheritance in
                           same project.
Access Modifier Example

Class Employee
{
   Private int ID;
   Private string NAME;
   Public void GetDetails()
            {
                      --------
            }
   Public void ShowDetails()
            {
                      ----------
            }
}

Tips:- In construction of class prefer to use “Private” access for fields and “Public” access for methods.
       We can access a private field of class by defining it into a public method of that class.
C# Properties

 Properties are members that provide a flexible
  mechanism to read, write or compute the values of
  private fields
 Properties can be used as if they are public data
  members, but they are actually special methods
  called Accessors.
 It enables data to be accessed easily and still helps
  promote the safety and flexibility of methods.
Accessors of Properties

 GET: To read value from the field


 SET: To write Value into the field


Tip:- SET uses an implicit parameter called “Value”, whose
  type is the type of the property within its declaration.
Tip:- The methods in which argument are not passed are
  called accessor.
Implementation of Properties

Using System;
Class Employee
{
    private int ID;
    public int IDNO
    {
              get
              {
                return ID;
              }
              set
              {
                 ID=Value;
              }
    }
}
Public static void main(String []args)
{
    Employee e1= new Employee();
    e1.IDNO= 1010
    C.W.L(“The given value of IDNO IS:”+ e1.IDNO)
}
Categories of C# Properties

 Read Only Properties:- properties that have only
                  GET accessor.
 Write Only Properties:- properties that have only
                  SET accessor.
 Read/Write Properties:- Having both GET and SET
                  accessor.
 Auto-Implemented Properties:- When no additional logic is required, we
  can declare properties as shown below
Public int EMPNO
{
  get;
  set;
}
Tip:- To create a read-only auto- implemented property, give it a private SET
  accessor
Tip:- Auto-implemented property must declare both GET and SET accessor.
Restrictions on Access modifiers on Accessor:

 You can use accessor modifiers only if the property
  or Indexer has both GET and SET accessor. In this
  case the modifier is permitted on only one of the two
  accessors.
 The accessibility level on the accessor must be more
  restrictive than the accessibility level on the property
  or Indexer itself.
 If the property or indexer has an override
  modifier, the accessor modifiers must match the
  accessor of the overridden accessor.
Indexer

It allow instances of a class to be indexed just like arrays.
   Indexers resemble properties except that their accessor
   takes parameters. It allow us to manipulate a field of
   class which is a collection or array
Some facts about Indexes:-
 The „this‟ keyword is used to define the indexer.
 The „Value‟ keyword is used to define the value being
   assigned by the SET indexer.
 Indexer do not have to be indexed by an integer value.
 It is up to you to define the specific look-up mechanism.
Example of Indexer
using System;
     class IntIndexer
     {
       private string[] myData;
         public IntIndexer(int size)         //constructor to initialize the array
         {
           myData = new string[size];
         }
         public string this[int pos]
         {
            get
           {
              return myData[pos];
            }
            set
           {
              myData[pos] = value;
            }
         }
         static void Main(string[] args)
         {
           int size = 10;
             IntIndexer myInd = new IntIndexer(size);
             myInd[9] = "Some Value";
             myInd[3] = "Another Value";
             myInd[5] = "Any Value";
             Console.WriteLine("nIndexer Outputn");
             for (int i=0; i < size; i++)
             {
               Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]);
             }
         }
     }
Difference b/w Property and Indexer

              Properties                                 Indexers

•Allow methods to be called as if they    •Allow elements of an internal
were public data member.                  collection of an object to be accessed by
                                          using array notation on the object itself.
•Can be a static or an instance member.
                                          •Must be an instance member.
•Supports shortened syntax with auto-
implemented properties.                   •Does not support shortened syntax.
Advantages of Encapsulation

 Protection
 Consistency
 Allows change
Inheritance

 A class which is a subtype of a more general class is said
  to be inherited from it.
 The sub-class inherits the base class‟ data members and
  member functions
 A sub-class has all data members of its base-class plus its
  own
 A sub-class has all member functions of its base class
  (with changes) plus its own

 Tips:- Every class in C# is Inherited from System.Object
  Class of C#.(Base Class)
Is-a Relationship in Inheritance



                                             Animal
Generalization




                                Mammal                            Reptile




                                                                            Specialization
                     Rodent             Primate            Cats


                 Mouse        Squirel             Rabbit

                         Mammal IS-A Animal, Mammal HAS-A Cat
Inheritance: BaseClass
using System;
    public class ParentClass
    {
      public ParentClass()
      {
        Console.WriteLine("Parent Constructor.");
      }
        public void print()
        {
          Console.WriteLine("I'm a Parent Class.");
        }
    }
    public class ChildClass : ParentClass
    {
      public ChildClass()
      {
        Console.WriteLine("Child Constructor.");
      }
        public static void Main()
        {
          ChildClass child = new ChildClass();
          child.print();
      }
    }
   Output:
    Parent Constructor.
    Child Constructor.
    I'm a Parent Class.
Type of Inheritance

 Single Inheritance:- When a derived class is derived
                      from a single base.

 Multiple Inheritance:- When a derived class is derived from
  more than one base class.

 Note:- C# does not support multiple Inheritance of classes.

 Tip:- In Inheritance private attributes of base class does not take part
  only public & protected attributes are inherited.

 Tip:- When two methods have same signature(name, attribute) in Base
  class and derived class, then the derived class method will overwrite the
  base class method.
Base Keyword

 If there is Overwriting of method(having same name) in Base class and
  derive class, we can access the base class method by using “Base”
  keyword, but it can only use in derive class.

Example:-
Class baseclass()
  {
        public void message()
  }
Class deriveclass:baseclass
{
  Public void message()
  {
        Base.message()
  }
}
New Keyword

 It give a new definition to the method().
 It is used before a method to define your objective to the compiler, so that it may understand
  exactly what you want to do.
 We can use “New” before the derived class method of same name as of base class to remove the
  compiler warning.
 The new keyword is used for data hiding, as it hides the base class method().

Example:-
Class baseclass()
   {
           public void message()
   }
Class deriveclass:baseclass
{
   New Public void message()
   {
           //some new definition for method
   }
}
Constructor & Destructor in Inheritance

 They are not inherited from base class to derived
  class
 But we can explicitly invokes base class constructors
  with derive class using Base keyword.
 The sequence of invoke for constructors are


 Constructor                         Destructor
                       Base Class




                      Derived Class
Example of Constructor
Class Myclass()
{
    Public Myclass()
    {
    C.W.L(“Base Class Constructor!!”);
    }
    ~Myclass()
    {
          C.W.L(“Base Class Destructor!!”)
    }
}
Class Myderive:Myclass
{
    public Myderive()
    {
       C.W.L(“My derive class constructor!!”)
    }
    ~Myderive()
    {
       C.W.L(“My derive class Destructor!!”)
    }
}
Public static void main()
{
    Myderive ob= new Myderive();
}
Output:
My base class constructor!!
My derive class constructor!!
My derive class Destructor!!
My base class Destructor!!
Types of Constructors

   Default constructor:- Executed when object of class is created
   Static constructor:- executed once, when first object of class is created, Use to initialize static fields.
   Parametric constructor:- Use to initialize the fields

Example:-
Class employee
{
    Private int x
    Public employee() // default constructor
             {
                         x=10;
             }
    Public employee (int a) // parametric constructor
    {
             x=a;
    }
    Static employee() // static constructor
    {
             console.writeline(“my static constructor”)
    }
}
Difference between Finalize() and Dispose()

 Finalize():Implicit way of reclamation of object memory, when there are no longer
   any valid references to the object, is done by garbage collector calling Finalize
   method or destructor in C#.

 Dispose():In some cases we might want to release expensive resources like
   windows handles, database connection, file system etc explicitly once we are
   finished using those object. Instead of depending on garbage collector for freeing up
   those expensive resources we can explicitly releases those resources by
   implementing Dispose method of IDisposable interface.

 In C#, you can implement a Dispose method to explicitly deallocate resources.

 In a Dispose method, you clean up after an object yourself, without C#'s help.
   Dispose can be called both explicitly, and/or by the code in your destructor.

Note: Dispose() can be called even if other references to the object are alive.
Polymorphism

 One interface
 Multiple implementations
 Inheritance
 This relationship between virtual methods and the
  derived class methods that override them enables
  polymorphism.
 It allows you to invoke derived class methods
  through a base class reference during run-time.
Tip:- A base class object can hold reference of all
  derive class object, but wise versa is not possible.
Virtual Methods

 They are used to achieve run-time polymorphism in
  C#.
 A virtual method is needed to override with
  “Override” keyword.
 We can declare a virtual methods and property by
  using “Virtual” keyword.
Virtual Method Declaration

using System;
   public class DrawingObject
   {
     public virtual void Draw()
     {
        Console.WriteLine("I'm just a generic drawing object.");
     }
   }
public class Line : DrawingObject
   {
     public override void Draw()
     {
        Console.WriteLine("I'm a Line.");
     }
   }
   public class Circle : DrawingObject
   {
     public override void Draw()
     {
       Console.WriteLine("I'm a Circle.");
     }
   }
Implementing Polymorphism

using System;
  public class DrawDemo
  {
    public static int Main( )
    {
      DrawingObject[] dObj = new DrawingObject[3];
         dObj[0] = new Line();
         dObj[1] = new Circle();
         dObj[2] = new DrawingObject();
         foreach (DrawingObject iObj in dObj)
         {
           iObj.Draw();
         }
     }
   }
Tip:- We can not use the Virtual modifier with the Static, Abstract, Private or Override
   modifier.
Abstraction

   Abstract class is a class which contains one or
    more abstract method
   We can declare an abstract class using “Abstract”
    keyword.
   An abstract method is a method which declaration
    is given somewhere and its definition is given
    somewhere else.
   In general abstract methods are declare in Base
    class and their definition is given in derived class.
Syntax for abstract class and their methods

Abstract class myclass
{
   public abstract void message();
}
Class checkabs:myclass
{
   public override void message()
   {
            console.writeline(“my abstract method”)
   }
}
Class program
{
   static void main()
   {
            checkabs ob= new checkabs();
            ob.message();
   }
}
Tips

 We can create an object of abstract class, but we
  can‟t instantiation it.
 We can store the reference of a derive class in
  abstract class object.

Example:-
 {
 myclass ob= new checkabs();
 ob.message();
 }
Interfaces

 It is also a reference type same as class, but it can not
  contain any definition within it.
 It only declares the member within it.
 Interface are also known as class with restrictions.
 We can declare interface using “Interface” keyword
  , generally interface name start‟s with “I” latter.

Syntax:-
Interface Iface
{
  //member declaration
}
Tips for using Interface

 Interface can not contain any implementation
 Interface methods are implicitly public & abstract
 Interface member cannot be static or virtual
 Interface can‟t contain constructor or destructor.
 Any non-abstract class inheriting interface must
  implement all its members.
 Interface can contain events, indexes, methods and
  properties, but it can not contain fields.
Tips for Interface

 Interface can‟t be instantiated directly.
 Interface contain no implementation of methods.
 Classes and structs can inherit more than one
  interface.
 An interface can inherit another interface.
 We can inherit multiple interface in a derive class
 Note:- we must override the interface method in
  derive class only by using public access- specifier.
Syntax for Interface

 Public interface Iface1
{
     Void fun1()
}
 Class myclass:Ifun1
{
     Public void fun1()
     {
       console.writeline(“My Interface”)
     }
}
Sealed Class

 Sealed class are primarily used to prevent derivation.
 They can never be used as a base class
Syntax:-
  Sealed class mybase
  {
  }
Class myderive:mybase
{
  // Will raise an error
}
Sealed Method

 Sealed modifier prevents a methods to be overridden
  by a derived class.
 We can use “sealed” keyword to declare sealed
  method

 Tip:- we can‟t use sealed keyword with a base class
  method.
 Tip:- we can not use sealed keyword with a non-
  virtual method.
Example of sealed modifier

Class mybase
{
   public virtual void mymethods()
   {
           console.writeline(“my base class method”)
   }
}
Class derive1:mybase
{
   public sealed override void mymethod()
   {
           console.writeline(“my derive class method”)
   }
}
Class derived2:derived1
{
   // can‟t override sealed method
}
Summary
 What is Object Oriented Programming?
 Object-oriented programming is a method of
 implementation in which programs are organized
 as cooperative collections of objects, each of which
 represents an instance of some class, and whose
 classes are all members of one or more hierarchy of
 classes united via inheritance relationships

Más contenido relacionado

La actualidad más candente

Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
Doncho Minkov
 

La actualidad más candente (20)

Python - object oriented
Python - object orientedPython - object oriented
Python - object oriented
 
Access specifiers(modifiers) in java
Access specifiers(modifiers) in javaAccess specifiers(modifiers) in java
Access specifiers(modifiers) in java
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Php array
Php arrayPhp array
Php array
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented Programming
 
Python programming : Exceptions
Python programming : ExceptionsPython programming : Exceptions
Python programming : Exceptions
 
Java constructors
Java constructorsJava constructors
Java constructors
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming language
 
Introduction to C# Programming
Introduction to C# ProgrammingIntroduction to C# Programming
Introduction to C# Programming
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Virtual Functions | Polymorphism | OOP
Virtual Functions | Polymorphism | OOPVirtual Functions | Polymorphism | OOP
Virtual Functions | Polymorphism | OOP
 
Ch.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsCh.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objects
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Arrays in java language
Arrays in java languageArrays in java language
Arrays in java language
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 

Destacado

Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
thinkphp
 
Object Oriented Concept
Object Oriented ConceptObject Oriented Concept
Object Oriented Concept
smj
 
Principles and advantages of oop ppt
Principles and advantages of oop pptPrinciples and advantages of oop ppt
Principles and advantages of oop ppt
daxesh chauhan
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and Design
Haitham El-Ghareeb
 

Destacado (19)

Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01
 
Basic concepts of object oriented programming
Basic concepts of object oriented programmingBasic concepts of object oriented programming
Basic concepts of object oriented programming
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017
 
Go for Object Oriented Programmers or Object Oriented Programming without Obj...
Go for Object Oriented Programmers or Object Oriented Programming without Obj...Go for Object Oriented Programmers or Object Oriented Programming without Obj...
Go for Object Oriented Programmers or Object Oriented Programming without Obj...
 
Object Oriented Approach for Software Development
Object Oriented Approach for Software DevelopmentObject Oriented Approach for Software Development
Object Oriented Approach for Software Development
 
Concepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming LanguagesConcepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming Languages
 
Object Oriented Concept
Object Oriented ConceptObject Oriented Concept
Object Oriented Concept
 
Need of object oriented programming
Need of object oriented programmingNeed of object oriented programming
Need of object oriented programming
 
OOP java
OOP javaOOP java
OOP java
 
Principles and advantages of oop ppt
Principles and advantages of oop pptPrinciples and advantages of oop ppt
Principles and advantages of oop ppt
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Object-oriented concepts
Object-oriented conceptsObject-oriented concepts
Object-oriented concepts
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
 
Structured Vs, Object Oriented Analysis and Design
Structured Vs, Object Oriented Analysis and DesignStructured Vs, Object Oriented Analysis and Design
Structured Vs, Object Oriented Analysis and Design
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and Design
 
Slideshare ppt
Slideshare pptSlideshare ppt
Slideshare ppt
 

Similar a Object-oriented programming

Is2215 lecture2 student(2)
Is2215 lecture2 student(2)Is2215 lecture2 student(2)
Is2215 lecture2 student(2)
dannygriff1
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
saryu2011
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
Zafor Iqbal
 

Similar a Object-oriented programming (20)

201005 accelerometer and core Location
201005 accelerometer and core Location201005 accelerometer and core Location
201005 accelerometer and core Location
 
oopm 2.pdf
oopm 2.pdfoopm 2.pdf
oopm 2.pdf
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .Net
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
object oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMobject oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoM
 
Oops
OopsOops
Oops
 
Php oop (1)
Php oop (1)Php oop (1)
Php oop (1)
 
My c++
My c++My c++
My c++
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Is2215 lecture2 student(2)
Is2215 lecture2 student(2)Is2215 lecture2 student(2)
Is2215 lecture2 student(2)
 
python.pptx
python.pptxpython.pptx
python.pptx
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Unit3 packages &amp; interfaces
Unit3 packages &amp; interfacesUnit3 packages &amp; interfaces
Unit3 packages &amp; interfaces
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
 
Beginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHPBeginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHP
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
JavaTutorials.ppt
JavaTutorials.pptJavaTutorials.ppt
JavaTutorials.ppt
 

Último

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Último (20)

2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 

Object-oriented programming

  • 2. Procedural Approach  Focus is on procedures  All data is shared: no protection  More difficult to modify  Hard to manage complexity
  • 3. OOPs Concepts  It is a system modeling technique in which the system is design with using discrete objects. The basic components of OOP’s are:-  Class:- It is written description of objects, It is collection of properties and behaviors.  Object:- They are real time things, something that exist, something that is used. Object is anything that is identifiable as a single material item.
  • 4. Objects and Classes  Classes reflect concepts, objects reflect instances that embody those concepts. object class girl Jodie Daria Jane Brittany
  • 5. Objects and Classes  Class  Object  Visible in source code  Own copy of data  The code is not  Active in running duplicated program  Occupies memory  Has the set of operations given in the class
  • 6. Objects and Classes  A class captures the common properties of the objects instantiated from it  A class characterizes the common behavior of all the objects that are its instances
  • 7. Instantiation  An Object is instantiated from a Class MyClass1 ob; ob = new MyClass1; Objects without memory is called Object and Objects with memory is called Instance. Note:- Only instance of classes are used in the program.
  • 8. Different Types of Variables:  Class Variable: They are Static members and accessed with the name of class rather than reference to objects. (by using “Static” keyword)  Instance Variable: They are used with instance not through class.  Local Variable: They are defined within a method
  • 9. Examples of Variables Class Employee { private static int C_vbl; private int I_vbl; Public void Class_Method() { int L_variable=100; } }
  • 10. Implementation of Static/Class Variable  class Test  {  public int rollNo;  public int mathsMarks;  public static int totalMathMarks;  }  class TestDemo  {  public static void main()  {  Test ob = new Test();  ob.rollNo = 1;  ob.mathsMarks = 40;  ob.rollNo = 2;  ob.mathsMarks = 43;  Test.totalMathsMarks = ob.mathsMarks + ob.mathsMarks;  }  }
  • 11. Properties of OOP‟s Key Concepts of Object Orientation  Encapsulation  Abstraction  Inheritance  Polymorphism
  • 12. Data Encapsulation How the object *should* be used. It allow you to hide internal state of objects and abstract access to it though type members such as Access Modifiers, methods, properties, and indexers.
  • 13. Access Modifiers C# provides us following 5 access modifiers:  Private: Used within the same class  Protected: Can be used by Inheritance class  Public: Can be excess by anyone  Internal: Can be used within the same project  Protected Internal: Can be used by Inheritance in same project.
  • 14. Access Modifier Example Class Employee { Private int ID; Private string NAME; Public void GetDetails() { -------- } Public void ShowDetails() { ---------- } } Tips:- In construction of class prefer to use “Private” access for fields and “Public” access for methods. We can access a private field of class by defining it into a public method of that class.
  • 15. C# Properties  Properties are members that provide a flexible mechanism to read, write or compute the values of private fields  Properties can be used as if they are public data members, but they are actually special methods called Accessors.  It enables data to be accessed easily and still helps promote the safety and flexibility of methods.
  • 16. Accessors of Properties  GET: To read value from the field  SET: To write Value into the field Tip:- SET uses an implicit parameter called “Value”, whose type is the type of the property within its declaration. Tip:- The methods in which argument are not passed are called accessor.
  • 17. Implementation of Properties Using System; Class Employee { private int ID; public int IDNO { get { return ID; } set { ID=Value; } } } Public static void main(String []args) { Employee e1= new Employee(); e1.IDNO= 1010 C.W.L(“The given value of IDNO IS:”+ e1.IDNO) }
  • 18. Categories of C# Properties  Read Only Properties:- properties that have only GET accessor.  Write Only Properties:- properties that have only SET accessor.  Read/Write Properties:- Having both GET and SET accessor.  Auto-Implemented Properties:- When no additional logic is required, we can declare properties as shown below Public int EMPNO { get; set; } Tip:- To create a read-only auto- implemented property, give it a private SET accessor Tip:- Auto-implemented property must declare both GET and SET accessor.
  • 19. Restrictions on Access modifiers on Accessor:  You can use accessor modifiers only if the property or Indexer has both GET and SET accessor. In this case the modifier is permitted on only one of the two accessors.  The accessibility level on the accessor must be more restrictive than the accessibility level on the property or Indexer itself.  If the property or indexer has an override modifier, the accessor modifiers must match the accessor of the overridden accessor.
  • 20. Indexer It allow instances of a class to be indexed just like arrays. Indexers resemble properties except that their accessor takes parameters. It allow us to manipulate a field of class which is a collection or array Some facts about Indexes:-  The „this‟ keyword is used to define the indexer.  The „Value‟ keyword is used to define the value being assigned by the SET indexer.  Indexer do not have to be indexed by an integer value.  It is up to you to define the specific look-up mechanism.
  • 21. Example of Indexer using System; class IntIndexer { private string[] myData; public IntIndexer(int size) //constructor to initialize the array { myData = new string[size]; } public string this[int pos] { get { return myData[pos]; } set { myData[pos] = value; } } static void Main(string[] args) { int size = 10; IntIndexer myInd = new IntIndexer(size); myInd[9] = "Some Value"; myInd[3] = "Another Value"; myInd[5] = "Any Value"; Console.WriteLine("nIndexer Outputn"); for (int i=0; i < size; i++) { Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]); } } }
  • 22. Difference b/w Property and Indexer Properties Indexers •Allow methods to be called as if they •Allow elements of an internal were public data member. collection of an object to be accessed by using array notation on the object itself. •Can be a static or an instance member. •Must be an instance member. •Supports shortened syntax with auto- implemented properties. •Does not support shortened syntax.
  • 23. Advantages of Encapsulation  Protection  Consistency  Allows change
  • 24. Inheritance  A class which is a subtype of a more general class is said to be inherited from it.  The sub-class inherits the base class‟ data members and member functions  A sub-class has all data members of its base-class plus its own  A sub-class has all member functions of its base class (with changes) plus its own  Tips:- Every class in C# is Inherited from System.Object Class of C#.(Base Class)
  • 25. Is-a Relationship in Inheritance Animal Generalization Mammal Reptile Specialization Rodent Primate Cats Mouse Squirel Rabbit Mammal IS-A Animal, Mammal HAS-A Cat
  • 26. Inheritance: BaseClass using System; public class ParentClass { public ParentClass() { Console.WriteLine("Parent Constructor."); } public void print() { Console.WriteLine("I'm a Parent Class."); } } public class ChildClass : ParentClass { public ChildClass() { Console.WriteLine("Child Constructor."); } public static void Main() { ChildClass child = new ChildClass(); child.print(); } }  Output: Parent Constructor. Child Constructor. I'm a Parent Class.
  • 27. Type of Inheritance  Single Inheritance:- When a derived class is derived from a single base.  Multiple Inheritance:- When a derived class is derived from more than one base class.  Note:- C# does not support multiple Inheritance of classes.  Tip:- In Inheritance private attributes of base class does not take part only public & protected attributes are inherited.  Tip:- When two methods have same signature(name, attribute) in Base class and derived class, then the derived class method will overwrite the base class method.
  • 28. Base Keyword  If there is Overwriting of method(having same name) in Base class and derive class, we can access the base class method by using “Base” keyword, but it can only use in derive class. Example:- Class baseclass() { public void message() } Class deriveclass:baseclass { Public void message() { Base.message() } }
  • 29. New Keyword  It give a new definition to the method().  It is used before a method to define your objective to the compiler, so that it may understand exactly what you want to do.  We can use “New” before the derived class method of same name as of base class to remove the compiler warning.  The new keyword is used for data hiding, as it hides the base class method(). Example:- Class baseclass() { public void message() } Class deriveclass:baseclass { New Public void message() { //some new definition for method } }
  • 30. Constructor & Destructor in Inheritance  They are not inherited from base class to derived class  But we can explicitly invokes base class constructors with derive class using Base keyword.  The sequence of invoke for constructors are  Constructor Destructor Base Class Derived Class
  • 31. Example of Constructor Class Myclass() { Public Myclass() { C.W.L(“Base Class Constructor!!”); } ~Myclass() { C.W.L(“Base Class Destructor!!”) } } Class Myderive:Myclass { public Myderive() { C.W.L(“My derive class constructor!!”) } ~Myderive() { C.W.L(“My derive class Destructor!!”) } } Public static void main() { Myderive ob= new Myderive(); } Output: My base class constructor!! My derive class constructor!! My derive class Destructor!! My base class Destructor!!
  • 32. Types of Constructors  Default constructor:- Executed when object of class is created  Static constructor:- executed once, when first object of class is created, Use to initialize static fields.  Parametric constructor:- Use to initialize the fields Example:- Class employee { Private int x Public employee() // default constructor { x=10; } Public employee (int a) // parametric constructor { x=a; } Static employee() // static constructor { console.writeline(“my static constructor”) } }
  • 33. Difference between Finalize() and Dispose()  Finalize():Implicit way of reclamation of object memory, when there are no longer any valid references to the object, is done by garbage collector calling Finalize method or destructor in C#.  Dispose():In some cases we might want to release expensive resources like windows handles, database connection, file system etc explicitly once we are finished using those object. Instead of depending on garbage collector for freeing up those expensive resources we can explicitly releases those resources by implementing Dispose method of IDisposable interface.  In C#, you can implement a Dispose method to explicitly deallocate resources.  In a Dispose method, you clean up after an object yourself, without C#'s help. Dispose can be called both explicitly, and/or by the code in your destructor. Note: Dispose() can be called even if other references to the object are alive.
  • 34. Polymorphism  One interface  Multiple implementations  Inheritance  This relationship between virtual methods and the derived class methods that override them enables polymorphism.  It allows you to invoke derived class methods through a base class reference during run-time. Tip:- A base class object can hold reference of all derive class object, but wise versa is not possible.
  • 35. Virtual Methods  They are used to achieve run-time polymorphism in C#.  A virtual method is needed to override with “Override” keyword.  We can declare a virtual methods and property by using “Virtual” keyword.
  • 36. Virtual Method Declaration using System; public class DrawingObject { public virtual void Draw() { Console.WriteLine("I'm just a generic drawing object."); } } public class Line : DrawingObject { public override void Draw() { Console.WriteLine("I'm a Line."); } } public class Circle : DrawingObject { public override void Draw() { Console.WriteLine("I'm a Circle."); } }
  • 37. Implementing Polymorphism using System; public class DrawDemo { public static int Main( ) { DrawingObject[] dObj = new DrawingObject[3]; dObj[0] = new Line(); dObj[1] = new Circle(); dObj[2] = new DrawingObject(); foreach (DrawingObject iObj in dObj) { iObj.Draw(); } } } Tip:- We can not use the Virtual modifier with the Static, Abstract, Private or Override modifier.
  • 38. Abstraction  Abstract class is a class which contains one or more abstract method  We can declare an abstract class using “Abstract” keyword.  An abstract method is a method which declaration is given somewhere and its definition is given somewhere else.  In general abstract methods are declare in Base class and their definition is given in derived class.
  • 39. Syntax for abstract class and their methods Abstract class myclass { public abstract void message(); } Class checkabs:myclass { public override void message() { console.writeline(“my abstract method”) } } Class program { static void main() { checkabs ob= new checkabs(); ob.message(); } }
  • 40. Tips  We can create an object of abstract class, but we can‟t instantiation it.  We can store the reference of a derive class in abstract class object. Example:- { myclass ob= new checkabs(); ob.message(); }
  • 41. Interfaces  It is also a reference type same as class, but it can not contain any definition within it.  It only declares the member within it.  Interface are also known as class with restrictions.  We can declare interface using “Interface” keyword , generally interface name start‟s with “I” latter. Syntax:- Interface Iface { //member declaration }
  • 42. Tips for using Interface  Interface can not contain any implementation  Interface methods are implicitly public & abstract  Interface member cannot be static or virtual  Interface can‟t contain constructor or destructor.  Any non-abstract class inheriting interface must implement all its members.  Interface can contain events, indexes, methods and properties, but it can not contain fields.
  • 43. Tips for Interface  Interface can‟t be instantiated directly.  Interface contain no implementation of methods.  Classes and structs can inherit more than one interface.  An interface can inherit another interface.  We can inherit multiple interface in a derive class  Note:- we must override the interface method in derive class only by using public access- specifier.
  • 44. Syntax for Interface  Public interface Iface1 { Void fun1() }  Class myclass:Ifun1 { Public void fun1() { console.writeline(“My Interface”) } }
  • 45. Sealed Class  Sealed class are primarily used to prevent derivation.  They can never be used as a base class Syntax:- Sealed class mybase { } Class myderive:mybase { // Will raise an error }
  • 46. Sealed Method  Sealed modifier prevents a methods to be overridden by a derived class.  We can use “sealed” keyword to declare sealed method  Tip:- we can‟t use sealed keyword with a base class method.  Tip:- we can not use sealed keyword with a non- virtual method.
  • 47. Example of sealed modifier Class mybase { public virtual void mymethods() { console.writeline(“my base class method”) } } Class derive1:mybase { public sealed override void mymethod() { console.writeline(“my derive class method”) } } Class derived2:derived1 { // can‟t override sealed method }
  • 48. Summary  What is Object Oriented Programming?  Object-oriented programming is a method of implementation in which programs are organized as cooperative collections of objects, each of which represents an instance of some class, and whose classes are all members of one or more hierarchy of classes united via inheritance relationships