SlideShare una empresa de Scribd logo
1 de 21
Inheritance and Its types

Reusability




Inheritance

Re-usability is yet another imperative attribute of OOP. It is always fine if we could reuse
something that already exists rather than construct it again. It helps in saving time and money. It
also avoids the frustration and increase the reliability. Fortunately, C++ powerfully supports the
conception of reusability. The C++ classes can be reused in numerous ways. Once a class has
written and tested, it can be modified by other programmers to suit their requirements.


Inheritance is the idea to inherit the properties of one set to another set. This has also known as
class composition again. For example, classes A contains two-member function ads and subtracts
and class b contain two different functions multiply and divide. We want to use all these function
with one object then we need to use inheritance where class B inherits all the property of class,
which is public, but class B cannot use the private properties of class A. There are following
types of inheritance:

1. Single class Inheritance:




Single Class Inheritance

The derived class inherits some or all of the traits from the base class. A class can also inherit
properties from more than one class or from more than one level. A derived class with only one
base case is celled single inheritance. When class A has inherited in class has known as base
class and B class is know as derived class. Here only two classes have connected to each other.

2. Multilevel Inheritance:




Multilevel Inheritance

In this type of inheritance, there are number of level and it has used in that cases where we want
to use all properties in number of levels according to the requirement. It is not unusual that a
class is derived from another derived class. The class a serves as a base class for the derived
class B, which in turn serves as a base class for the derived class C. The class B is known as
intermediary base class since it provides a connection for the inheritance between A and C.

3. Multiple Inheritances:




3. Multiple Inheritances:

A class can inherit the attributes of two or more classes. This is known as multiple inheritances.
Multiple inheritances allow us to join the features of a number of existing classes as a starting
point for defining new classes. It is like a child inheriting the physical features of one parent and
the brainpower of another.

4. Hierarchical Inheritance:
Hierarchical Inheritance:

This type of inheritance helps us to generate a baseless for number of classes and those numbers
of classes can have promoted their branches of number of class.

5. Hybrid Inheritance:




Hybrid Inheritance:

In this type of inheritance, we can have combination of number of inheritances but this can
produce an error of using same name function from no of classes, which will bother the compiler
to how to use the functions. Therefore, it will generate errors in the program. This has known as
ambiguity o


Java Final Keyword
22/05/2008

        A java variable can be declared using the keyword final. Then the final variable can be assigned
        only once.
        A variable that is declared as final and not initialized is called a blank final variable. A blank final
        variable forces the constructors to initialise it.
        Java classes declared as final cannot be extended. Restricting inheritance!
        Methods declared as final cannot be overridden. In methods private is equal to final, but in
        variables it is not.
        final parameters – values of the parameters cannot be changed after initialization. Do a small
        java exercise to find out the implications of final parameters in method overriding.
        Java local classes can only reference local variables and parameters that are declared as final.
A visible advantage of declaring a java variable as static final is, the compiled java class results in
         faster performance.
         ACESS SPECIFIERS
         So here the Laptop is an object that is designed to hide its complexity.
         How to abstract: - By using Access Specifiers

         .Net has five access Specifiers

         Public -- Accessible outside the class through object reference.

         Private -- Accessible inside the class only through member functions.

         Protected -- Just like private but Accessible in derived classes also through
         member
         functions.

         Internal -- Visible inside the assembly. Accessible through objects.

         Protected Internal -- Visible inside the assembly through objects and in derived
         classes outside the assembly through member functions.

Inheritance:



Inheritance is a process of deriving the new class from already existing class

C# is a complete object oriented programming language. Inheritance is one of the primary
concepts of object-oriented programming. It allows you to reuse existing code. Through
effective use of inheritance, you can save lot of time in your programming and also reduce
errors, which in turn will increase the quality of work and productivity. A simple example to
understand inheritance in C#.




Using System;

PublicclassBaseClass

{

    PublicBaseClass ()

    {

        Console.WriteLine ("Base Class Constructor executed");

    }
Publicvoid Write ()

    {

        Console.WriteLine ("Write method in Base Class executed");

    }

}



PublicclassChildClass: BaseClass

{



    PublicChildClass ()

    {

        Console.WriteLine("Child Class Constructor executed");

    }



    Publicstaticvoid Main ()

    {

        ChildClass CC = newChildClass ();

        CC.Write ();

    }

}



In the Main () method in ChildClass we create an instance of childclass. Then we call the
write () method. If you observe the ChildClass does not have a write() method in it. This
write () method has been inherited from the parent BaseClass.



The output of the above program is

Output:
Base Class Constructor executed
    Child Class Constructor executed
    Write method in Base Class executed



this output proves that when we create an instance of a child class, the base class
constructor will automatically be called before the child class constructor. So in general Base
classes are automatically instantiated before derived classes.



In C# the syntax for specifying BaseClass and ChildClass relationship is shown below. The
base class is specified by adding a colon, ":", after the derived class identifier and then
specifying the base class name.



Syntax: class ChildClassName: BaseClass
        {
            //Body
        }



C# supports single class inheritance only. What this means is, your class can inherit from
only one base class at a time. In the code snippet below, class C is trying to inherit from
Class A and B at the same time. This is not allowed in C#. This will lead to a compile time

error: Class 'C' cannot have multiple base classes: 'A' and 'B'.



publicclassA

{

}

publicclassB

{

}

publicclassC : A, B

{

}
In C# Multi-Level inheritance is possible. Code snippet below demonstrates mlti-level
inheritance. Class B is derived from Class A. Class C is derived from Class B. So class C, will
have access to all members present in both Class A and Class B. As a result of multi-level
inheritance Class has access to A_Method(),B_Method() and C_Method().

Note: Classes can inherit from multiple interfaces at the same time. Interview Question:
How can you implement multiple inheritance in C#? Ans :Using Interfaces. We will talk
about interfaces in our later article.



Using System;

PublicclassA

{

    PublicvoidA_Method ()

    {

        Console.WriteLine ("Class A Method Called");

    }

}

PublicclassB: A

{

    PublicvoidB_Method ()

    {

        Console.WriteLine ("Class A Method Called");

    }

}

PublicclassC: B

{

    PublicvoidC_Method ()

    {

        Console.WriteLine ("Class A Method Called");
}



    Publicstaticvoid Main ()

    {

        C C1 = newC ();

        C1.A_Method ();

        C1.B_Method ();

        C1.C_Method ();

    }

}

When you derive a class from a base class, the derived class will inherit all members of the
base class except constructors. In the code snippet below class B will inherit both M1 and
M2 from Class A, but you cannot access M2 because of the private access modifier. Class
members declared with a private access modifier can be accessed only with in the class. We
will talk about access modifiers in our later article.

Common Interview Question: Are private class members inherited to the derived
class?



Ans: Yes, the private members are also inherited in the derived class but we will not be
able to access them. Trying to access a private base class member in the derived class will
report a compile time error.



Using System;

PublicclassA

{

Publicvoid M1 ()

{

}

Privatevoid M2 ()

{
}

}



PublicclassB: A

{

Publicstaticvoid Main ()

{

B B1 = newB ();

B1.M1 ();

//Error, Cannot access private member M2

//B1.M2 ();

}

}

Method Hiding and Inheritance We will look at an example of how to hide a method in C#.
The Parent class has a write () method which is available to the child class. In the child class
I have created a new write () method. So, now if I create an instance of child class and call
the write () method, the child class write () method will be called. The child class is hiding
the base class write () method. This is called method hiding.

If we want to call the parent class write () method, we would have to type cast the child
object to Parent type and then call the write () method as shown in the code snippet below.




Using System;

PublicclassParent

{

    Publicvoid Write ()

    {

        Console.WriteLine ("Parent Class write method");

    }
}



PublicclassChild: Parent

{

    Publicnewvoid Write ()

    {

        Console.WriteLine ("Child Class write method");

    }



    Publicstaticvoid Main ()

    {

        Child C1 = newChild ();

        C1.Write ();

        //Type caste C1 to be of type Parent and call Write () method

        ((Parent) C1).Write ();

    }

}




Polymorphism:



When a message can be processed in different ways is called polymorphism. Polymorphism
means many forms.



Polymorphism is one of the fundamental concepts of OOP.



Polymorphism provides following features:
It allows you to invoke methods of derived class through base class reference during
       runtime.
       It has the ability for classes to provide different implementations of methods that are
       called through the same name.
Polymorphism is of two types:



   1. Compile time polymorphism/Overloading
   2. Runtime polymorphism/Overriding

Compile Time Polymorphism


Compile time polymorphism is method and operators overloading. It is also called early
binding.



In method overloading method performs the different task at the different input
parameters.



Runtime Time Polymorphism



Runtime time polymorphism is done using inheritance and virtual functions. Method
overriding is called runtime polymorphism. It is also called late binding.



When overriding a method, you change the behavior of the method for the derived class.
Overloading a method simply involves having another method with the same prototype.



Caution:Don't confused method overloading with method overriding, they are different,
unrelated concepts. But they sound similar.



Method overloading has nothing to do with inheritance or virtual methods.



Following are examples of methods having different overloads:



void area(int side);
void area(int l, int b);

void area(float radius);



Practical example of Method Overloading (Compile Time Polymorphism)



using System;



namespacemethod_overloading

{

    classProgram

    {

        publicclassPrint

        {



            publicvoid display(string name)

            {

                Console.WriteLine ("Your name is : " + name);

            }



            publicvoid display(int age, float marks)

            {

                Console.WriteLine ("Your age is : " + age);

                Console.WriteLine ("Your marks are :" + marks);

            }

        }



        staticvoid Main(string[] args)
{



            Printobj = newPrint ();

            obj.display ("George");

            obj.display (34, 76.50f);

            Console.ReadLine ();

        }

    }

}



Note:In the code if you observe display method is called two times. Display method will
work according to the number of parameters and type of parameters.



When and why to use method overloading



Use method overloading in situation where you want a class to be able to do something, but
there is more than one possibility for what information is supplied to the method that carries
out the task.



You should consider overloading a method when you for some reason need a couple of
methods that take different parameters, but conceptually do the same thing.



Method overloading showing many forms.



using System;



namespacemethod_overloading_polymorphism

{

    ClassProgram
{

    PublicclassShape

    {

        Publicvoid Area (float r)

        {

            float a = (float)3.14 * r;

            // here we have used function overload with 1 parameter.

            Console.WriteLine ("Area of a circle: {0}",a);

        }



        PublicvoidArea(float l, float b)

        {

            float x = (float)l* b;

            // here we have used function overload with 2 parameters.

            Console.WriteLine ("Area of a rectangle: {0}",x);



        }



        publicvoid Area(float a, float b, float c)

        {

            float s = (float)(a*b*c)/2;

            // here we have used function overload with 3 parameters.

            Console.WriteLine ("Area of a circle: {0}", s);

        }

    }



    Staticvoid Main (string[] args)
{

            Shapeob = newShape ();

            ob.Area(2.0f);

            ob.Area(20.0f,30.0f);

            ob.Area(2.0f,3.0f,4.0f);

            Console.ReadLine ();

        }

    }

}



Things to keep in mind while method overloading



If you use overload for method, there are couple of restrictions that the compiler imposes.



The rule is that overloads must be different in their signature, which means the name and
the number and type of parameters.



There is no limit to how many overload of a method you can have. You simply declare them
in a class, just as if they were different methods that happened to have the same name.




Method Overriding:



Whereas Overridingmeans changing the functionality of a method without changing the
signature. We can override a function in base class by creating a similar function in derived
class. This is done by using virtual/overridekeywords.

Base class method has to be marked with virtual keyword and we can override it in derived
class using override keyword.

Derived class method will completely overrides base class method i.e. when we refer base
class object created by casting derived class object a method in derived class will be called.
Example:
// Base class
publicclassBaseClass
{
publicvirtualvoid Method1()
{
Console.Write("Base Class Method");
}
}
// Derived class
publicclassDerivedClass : BaseClass
{
publicoverridevoid Method1()
{
Console.Write("Derived Class Method");
}
}
// Using base and derived class
publicclassSample
{
publicvoidTestMethod()
{
// calling the overriden method
DerivedClassobjDC = newDerivedClass();
objDC.Method1();
 // calling the baesd class method
BaseClassobjBC = (BaseClass)objDC;
objDC.Method1();
}
}

Output
---------------------
Derived Class Method

Derived Class Method
Constructors and Destructors:



Classes have complicated internal structures, including data and functions, object
initialization and cleanup for classes is much more complicated than it is for simple data
structures. Constructors and destructors are special member functions of classes that are
used to construct and destroy class objects. Construction may involve memory allocation
and initialization for objects. Destruction may involve cleanup and deallocation of memory
for objects.
Constructors and destructors do not have return types nor can they return values.
         References and pointers cannot be used on constructors and destructors because
         their addresses cannot be taken.
         Constructors cannot be declared with the keyword virtual.
         Constructors and destructors cannot be declared const, or volatile.
         Unions cannot contain class objects that have constructors or destructors.

Constructors and destructors obey the same access rules as member functions. For
example, if you declare a constructor with protected access, only derived classes and friends
can use it to create class objects.
The compiler automatically calls constructors when defining class objects and calls
destructors when class objects go out of scope. A constructor does not allocate memory for
the class object it’s this pointer refers to, but may allocate storage for more objects than its
class object refers to. If memory allocation is required for objects, constructors can
explicitly call the new operator. During cleanup, a destructor may release objects allocated
by the corresponding constructor. To release objects, use the delete operator.



Example of Constructor

classC
{

     privateint x;

     privateint y;

     public C (int i, int j)

     {

             x = i;

             y = j;

     }

     publicvoid display ()

     {

            Console.WriteLine(x + "i+" + y);

     }

}

Example of Destructor

classD
{

      public D ()

      {

          // constructor

      }

      ~D ()

      {

          // Destructor

      }

}anoop and explain its principles in java?



What is an oop and explain its principles in java?
Answer:

Java is an object oriented programming language. The main concepts used in Java are:

Class
Defines the abstract characteristics of a thing (object), including the thing's characteristics (its attributes,
fields or properties) and the thing's behaviors (the things it can do, or methods, operations or features).
One might say that a class is a blueprint or factory that describes the nature of something. For example,
the class Dog would consist of traits shared by all dogs, such as breed and fur color (characteristics), and
the ability to bark and sit (behaviors). Classes provide modularity and structure in an object-oriented
computer program. A class should typically be recognizable to a non-programmer familiar with the
problem domain, meaning that the characteristics of the class should make sense in context. Also, the
code for a class should be relatively self-contained (generally using encapsulation). Collectively, the
properties and methods defined by a class are called members.

Object
A pattern (exemplar) of a class. The class of Dog defines all possible dogs by listing the characteristics
and behaviors they can have; the object Lassie is one particular dog, with particular versions of the
characteristics. A Dog has fur; Lassie has brown-and-white fur.

Instance
One can have an instance of a class or a particular object. The instance is the actual object created at
runtime. In programmer jargon, the Lassie object is an instance of the Dog class. The set of values of the
attributes of a particular object is called its state. The object consists of state and the behaviour that's
defined in the object's class.

Method
An object's abilities. In language, methods (sometimes referred to as "functions") are verbs. Lassie,
being a Dog, has the ability to bark. So bark() is one of Lassie's methods. She may have other methods as
well, for example sit() or eat() or walk() or save_timmy(). Within the program, using a method usually
affects only one particular object; all Dogs can bark, but you need only one particular dog to do the
barking.

Message passing
"The process by which an object sends data to another object or asks the other object to invoke a
method."Also known to some programming languages as interfacing. For example, the object called
Breeder may tell the Lassie object to sit by passing a "sit" message which invokes Lassie's "sit" method.
The syntax varies between languages, for example: [Lassie sit] in Objective-C. In Java, code-level
message passing corresponds to "method calling". Some dynamic languages use double-dispatch or
multi-dispatch to find and pass messages.

Inheritance
"Subclasses" are more specialized versions of a class, which inherit attributes and behaviors from their
parent classes, and can introduce their own.
For example, the class Dog might have sub-classes called Collie, Chihuahua, and GoldenRetriever. In this
case, Lassie would be an instance of the Collie subclass. Suppose the Dog class defines a method called
bark() and a property called furColor. Each of its sub-classes (Collie, Chihuahua, and GoldenRetriever)
will inherit these members, meaning that the programmer only needs to write the code for them once.
Each subclass can alter its inherited traits. For example, the Collie class might specify that the default
furColor for a collie is brown-and-white. The Chihuahua subclass might specify that the bark() method
produces a high pitch by default. Subclasses can also add new members. The Chihuahua subclass could
add a method called tremble(). So an individual chihuahua instance would use a high-pitched bark()
from the Chihuahua subclass, which in turn inherited the usual bark() from Dog. The chihuahua object
would also have the tremble() method, but Lassie would not, because she is a Collie, not a Chihuahua. In
fact, inheritance is an "a... is a" relationship between classes, while instantiation is an "is a" relationship
between an object and a class: a Collie is a Dog ("a... is a"), but Lassie is a Collie ("is a"). Thus, the object
named Lassie has the methods from both classes Collie and Dog.
Multiple inheritance is inheritance from more than one ancestor class, neither of these ancestors being
an ancestor of the other. For example, independent classes could define Dogs and Cats, and a Chimera
object could be created from these two which inherits all the (multiple) behavior of cats and dogs. This
is not always supported, as it can be hard both to implement and to use well.

Abstraction
Abstraction is simplifying complex reality by modelling classes appropriate to the problem, and working
at the most appropriate level of inheritance for a given aspect of the problem.
For example, Lassie the Dog may be treated as a Dog much of the time, a Collie when necessary to
access Collie-specific attributes or behaviors, and as an Animal (perhaps the parent class of Dog) when
counting Timmy's pets.
Abstraction is also achieved through Composition. For example, a class Car would be made up of an
Engine, Gearbox, Steering objects, and many more components. To build the Car class, one does not
need to know how the different components work internally, but only how to interface with them, i.e.,
send messages to them, receive messages from them, and perhaps make the different objects
composing the class interact with each other.

Encapsulation
Encapsulation conceals the functional details of a class from objects that send messages to it.
For example, the Dog class has a bark() method. The code for the bark() method defines exactly how a
bark happens (e.g., by inhale() and then exhale(), at a particular pitch and volume). Timmy, Lassie's
friend, however, does not need to know exactly how she barks. Encapsulation is achieved by specifying
which classes may use the members of an object. The result is that each object exposes to any class a
certain interface - those members accessible to that class. The reason for encapsulation is to prevent
clients of an interface from depending on those parts of the implementation that are likely to change in
future, thereby allowing those changes to be made more easily, that is, without changes to clients. For
example, an interface can ensure that puppies can only be added to an object of the class Dog by code
in that class. Members are often specified as public, protected or private, determining whether they are
available to all classes, sub-classes or only the defining class. Some languages go further: Java uses the
default access modifier to restrict access also to classes in the same package, C# and VB.NET reserve
some members to classes in the same assembly using keywords internal (C#) or Friend (VB.NET), and
Eiffel and C++ allow one to specify which classes may access any member.

Polymorphism
Polymorphism allows the programmer to treat derived class members just like their parent class'
members. More precisely, Polymorphism in object-oriented programming is the ability of objects
belonging to different data types to respond to method calls of methods of the same name, each one
according to an appropriate type-specific behavior. One method, or an operator such as +, -, or *, can be
abstractly applied in many different situations. If a Dog is commanded to speak(), this may elicit a bark().
However, if a Pig is commanded to speak(), this may elicit an oink(). They both inherit speak() from
Animal, but their derived class methods override the methods of the parent class; this is Overriding
Polymorphism. Overloading Polymorphism is the use of one method signature, or one operator such as
"+", to perform several different functions depending on the implementation. The "+" operator, for
example, may be used to perform integer addition, float addition, list concatenation, or string
concatenation. Any two subclasses of Number, such as Integer and Double, are expected to add
together properly in an OOP language. The language must therefore overload the addition operator, "+",
to work this way. This helps improve code readability. How this is implemented varies from language to
language, but most OOP languages support at least some level of overloading polymorphism. Many OOP
languages also support Parametric Polymorphism, where code is written without mention of any specific
type and thus can be used transparently with any number of new types. Pointers are an example of a
simple polymorphic routine that can be used with many different types of objects.
Decoupling
Decoupling allows for the separation of object interactions from classes and inheritance into distinct
layers of abstraction. A common use of decoupling is to polymorphically decouple the encapsulation,
which is the practice of using reusable code to prevent discrete code modules from interacting with
each other. However, in practice decoupling often involves trade-offs with regard to which patterns of
change to favor. The science of measuring these trade-offs in respect to actual change in an objective
way is still in its infancy.

Más contenido relacionado

La actualidad más candente

La actualidad más candente (19)

Inheritance
InheritanceInheritance
Inheritance
 
Inheritance in c++ by Manan Pasricha
Inheritance in c++ by Manan PasrichaInheritance in c++ by Manan Pasricha
Inheritance in c++ by Manan Pasricha
 
Inheritance
InheritanceInheritance
Inheritance
 
inhertance c++
inhertance c++inhertance c++
inhertance c++
 
Inheritance
InheritanceInheritance
Inheritance
 
OOP
OOPOOP
OOP
 
Inheritance
InheritanceInheritance
Inheritance
 
INHERTANCE , NARROW AND WIDENING
INHERTANCE , NARROW AND WIDENING INHERTANCE , NARROW AND WIDENING
INHERTANCE , NARROW AND WIDENING
 
EASY TO LEARN INHERITANCE IN C++
EASY TO LEARN INHERITANCE IN C++EASY TO LEARN INHERITANCE IN C++
EASY TO LEARN INHERITANCE IN C++
 
Java Classes methods and inheritance
Java Classes methods and inheritanceJava Classes methods and inheritance
Java Classes methods and inheritance
 
Inheritance in OOPS
Inheritance in OOPSInheritance in OOPS
Inheritance in OOPS
 
Java OOPS Concept
Java OOPS ConceptJava OOPS Concept
Java OOPS Concept
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
Java interface
Java interfaceJava interface
Java interface
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
 
Java non access modifiers
Java non access modifiersJava non access modifiers
Java non access modifiers
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
Hierarchical inheritance
Hierarchical inheritanceHierarchical inheritance
Hierarchical inheritance
 
Lecture 17
Lecture 17Lecture 17
Lecture 17
 

Destacado

46thingsthatbugpeopleplus1bonusslideshow 130322165436-phpapp01
46thingsthatbugpeopleplus1bonusslideshow 130322165436-phpapp0146thingsthatbugpeopleplus1bonusslideshow 130322165436-phpapp01
46thingsthatbugpeopleplus1bonusslideshow 130322165436-phpapp01Ganesh Amirineni
 
Learn BEM: CSS Naming Convention
Learn BEM: CSS Naming ConventionLearn BEM: CSS Naming Convention
Learn BEM: CSS Naming ConventionIn a Rocket
 
SEO: Getting Personal
SEO: Getting PersonalSEO: Getting Personal
SEO: Getting PersonalKirsty Hulse
 
How to Build a Dynamic Social Media Plan
How to Build a Dynamic Social Media PlanHow to Build a Dynamic Social Media Plan
How to Build a Dynamic Social Media PlanPost Planner
 

Destacado (6)

46thingsthatbugpeopleplus1bonusslideshow 130322165436-phpapp01
46thingsthatbugpeopleplus1bonusslideshow 130322165436-phpapp0146thingsthatbugpeopleplus1bonusslideshow 130322165436-phpapp01
46thingsthatbugpeopleplus1bonusslideshow 130322165436-phpapp01
 
Compiler 2011-8-re1
Compiler 2011-8-re1Compiler 2011-8-re1
Compiler 2011-8-re1
 
Мы принимаем культуру, чтобы научиться говорить
Мы принимаем культуру, чтобы научиться говоритьМы принимаем культуру, чтобы научиться говорить
Мы принимаем культуру, чтобы научиться говорить
 
Learn BEM: CSS Naming Convention
Learn BEM: CSS Naming ConventionLearn BEM: CSS Naming Convention
Learn BEM: CSS Naming Convention
 
SEO: Getting Personal
SEO: Getting PersonalSEO: Getting Personal
SEO: Getting Personal
 
How to Build a Dynamic Social Media Plan
How to Build a Dynamic Social Media PlanHow to Build a Dynamic Social Media Plan
How to Build a Dynamic Social Media Plan
 

Similar a Ganesh groups (20)

Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
Inheritance Inheritance
Inheritance
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
 
lecture 6.pdf
lecture 6.pdflecture 6.pdf
lecture 6.pdf
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
11 Inheritance.ppt
11 Inheritance.ppt11 Inheritance.ppt
11 Inheritance.ppt
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
Inheritance and Interfaces
Inheritance and InterfacesInheritance and Interfaces
Inheritance and Interfaces
 
C++ presentation
C++ presentationC++ presentation
C++ presentation
 
Opp concept in c++
Opp concept in c++Opp concept in c++
Opp concept in c++
 
INHERITANCE.pptx
INHERITANCE.pptxINHERITANCE.pptx
INHERITANCE.pptx
 
Only oop
Only oopOnly oop
Only oop
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
 
OOP Assign No.03(AP).pdf
OOP Assign No.03(AP).pdfOOP Assign No.03(AP).pdf
OOP Assign No.03(AP).pdf
 
7494610
74946107494610
7494610
 
Lecturespecial
LecturespecialLecturespecial
Lecturespecial
 
Inheritance
InheritanceInheritance
Inheritance
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
 
Lecture 12
Lecture 12Lecture 12
Lecture 12
 

Último

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
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.pdfAdmir Softic
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 

Último (20)

Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
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
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 

Ganesh groups

  • 1. Inheritance and Its types Reusability Inheritance Re-usability is yet another imperative attribute of OOP. It is always fine if we could reuse something that already exists rather than construct it again. It helps in saving time and money. It also avoids the frustration and increase the reliability. Fortunately, C++ powerfully supports the conception of reusability. The C++ classes can be reused in numerous ways. Once a class has written and tested, it can be modified by other programmers to suit their requirements. Inheritance is the idea to inherit the properties of one set to another set. This has also known as class composition again. For example, classes A contains two-member function ads and subtracts and class b contain two different functions multiply and divide. We want to use all these function with one object then we need to use inheritance where class B inherits all the property of class, which is public, but class B cannot use the private properties of class A. There are following types of inheritance: 1. Single class Inheritance: Single Class Inheritance The derived class inherits some or all of the traits from the base class. A class can also inherit properties from more than one class or from more than one level. A derived class with only one
  • 2. base case is celled single inheritance. When class A has inherited in class has known as base class and B class is know as derived class. Here only two classes have connected to each other. 2. Multilevel Inheritance: Multilevel Inheritance In this type of inheritance, there are number of level and it has used in that cases where we want to use all properties in number of levels according to the requirement. It is not unusual that a class is derived from another derived class. The class a serves as a base class for the derived class B, which in turn serves as a base class for the derived class C. The class B is known as intermediary base class since it provides a connection for the inheritance between A and C. 3. Multiple Inheritances: 3. Multiple Inheritances: A class can inherit the attributes of two or more classes. This is known as multiple inheritances. Multiple inheritances allow us to join the features of a number of existing classes as a starting point for defining new classes. It is like a child inheriting the physical features of one parent and the brainpower of another. 4. Hierarchical Inheritance:
  • 3. Hierarchical Inheritance: This type of inheritance helps us to generate a baseless for number of classes and those numbers of classes can have promoted their branches of number of class. 5. Hybrid Inheritance: Hybrid Inheritance: In this type of inheritance, we can have combination of number of inheritances but this can produce an error of using same name function from no of classes, which will bother the compiler to how to use the functions. Therefore, it will generate errors in the program. This has known as ambiguity o Java Final Keyword 22/05/2008 A java variable can be declared using the keyword final. Then the final variable can be assigned only once. A variable that is declared as final and not initialized is called a blank final variable. A blank final variable forces the constructors to initialise it. Java classes declared as final cannot be extended. Restricting inheritance! Methods declared as final cannot be overridden. In methods private is equal to final, but in variables it is not. final parameters – values of the parameters cannot be changed after initialization. Do a small java exercise to find out the implications of final parameters in method overriding. Java local classes can only reference local variables and parameters that are declared as final.
  • 4. A visible advantage of declaring a java variable as static final is, the compiled java class results in faster performance. ACESS SPECIFIERS So here the Laptop is an object that is designed to hide its complexity. How to abstract: - By using Access Specifiers .Net has five access Specifiers Public -- Accessible outside the class through object reference. Private -- Accessible inside the class only through member functions. Protected -- Just like private but Accessible in derived classes also through member functions. Internal -- Visible inside the assembly. Accessible through objects. Protected Internal -- Visible inside the assembly through objects and in derived classes outside the assembly through member functions. Inheritance: Inheritance is a process of deriving the new class from already existing class C# is a complete object oriented programming language. Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Through effective use of inheritance, you can save lot of time in your programming and also reduce errors, which in turn will increase the quality of work and productivity. A simple example to understand inheritance in C#. Using System; PublicclassBaseClass { PublicBaseClass () { Console.WriteLine ("Base Class Constructor executed"); }
  • 5. Publicvoid Write () { Console.WriteLine ("Write method in Base Class executed"); } } PublicclassChildClass: BaseClass { PublicChildClass () { Console.WriteLine("Child Class Constructor executed"); } Publicstaticvoid Main () { ChildClass CC = newChildClass (); CC.Write (); } } In the Main () method in ChildClass we create an instance of childclass. Then we call the write () method. If you observe the ChildClass does not have a write() method in it. This write () method has been inherited from the parent BaseClass. The output of the above program is Output:
  • 6. Base Class Constructor executed Child Class Constructor executed Write method in Base Class executed this output proves that when we create an instance of a child class, the base class constructor will automatically be called before the child class constructor. So in general Base classes are automatically instantiated before derived classes. In C# the syntax for specifying BaseClass and ChildClass relationship is shown below. The base class is specified by adding a colon, ":", after the derived class identifier and then specifying the base class name. Syntax: class ChildClassName: BaseClass { //Body } C# supports single class inheritance only. What this means is, your class can inherit from only one base class at a time. In the code snippet below, class C is trying to inherit from Class A and B at the same time. This is not allowed in C#. This will lead to a compile time error: Class 'C' cannot have multiple base classes: 'A' and 'B'. publicclassA { } publicclassB { } publicclassC : A, B { }
  • 7. In C# Multi-Level inheritance is possible. Code snippet below demonstrates mlti-level inheritance. Class B is derived from Class A. Class C is derived from Class B. So class C, will have access to all members present in both Class A and Class B. As a result of multi-level inheritance Class has access to A_Method(),B_Method() and C_Method(). Note: Classes can inherit from multiple interfaces at the same time. Interview Question: How can you implement multiple inheritance in C#? Ans :Using Interfaces. We will talk about interfaces in our later article. Using System; PublicclassA { PublicvoidA_Method () { Console.WriteLine ("Class A Method Called"); } } PublicclassB: A { PublicvoidB_Method () { Console.WriteLine ("Class A Method Called"); } } PublicclassC: B { PublicvoidC_Method () { Console.WriteLine ("Class A Method Called");
  • 8. } Publicstaticvoid Main () { C C1 = newC (); C1.A_Method (); C1.B_Method (); C1.C_Method (); } } When you derive a class from a base class, the derived class will inherit all members of the base class except constructors. In the code snippet below class B will inherit both M1 and M2 from Class A, but you cannot access M2 because of the private access modifier. Class members declared with a private access modifier can be accessed only with in the class. We will talk about access modifiers in our later article. Common Interview Question: Are private class members inherited to the derived class? Ans: Yes, the private members are also inherited in the derived class but we will not be able to access them. Trying to access a private base class member in the derived class will report a compile time error. Using System; PublicclassA { Publicvoid M1 () { } Privatevoid M2 () {
  • 9. } } PublicclassB: A { Publicstaticvoid Main () { B B1 = newB (); B1.M1 (); //Error, Cannot access private member M2 //B1.M2 (); } } Method Hiding and Inheritance We will look at an example of how to hide a method in C#. The Parent class has a write () method which is available to the child class. In the child class I have created a new write () method. So, now if I create an instance of child class and call the write () method, the child class write () method will be called. The child class is hiding the base class write () method. This is called method hiding. If we want to call the parent class write () method, we would have to type cast the child object to Parent type and then call the write () method as shown in the code snippet below. Using System; PublicclassParent { Publicvoid Write () { Console.WriteLine ("Parent Class write method"); }
  • 10. } PublicclassChild: Parent { Publicnewvoid Write () { Console.WriteLine ("Child Class write method"); } Publicstaticvoid Main () { Child C1 = newChild (); C1.Write (); //Type caste C1 to be of type Parent and call Write () method ((Parent) C1).Write (); } } Polymorphism: When a message can be processed in different ways is called polymorphism. Polymorphism means many forms. Polymorphism is one of the fundamental concepts of OOP. Polymorphism provides following features:
  • 11. It allows you to invoke methods of derived class through base class reference during runtime. It has the ability for classes to provide different implementations of methods that are called through the same name. Polymorphism is of two types: 1. Compile time polymorphism/Overloading 2. Runtime polymorphism/Overriding Compile Time Polymorphism Compile time polymorphism is method and operators overloading. It is also called early binding. In method overloading method performs the different task at the different input parameters. Runtime Time Polymorphism Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding. When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same prototype. Caution:Don't confused method overloading with method overriding, they are different, unrelated concepts. But they sound similar. Method overloading has nothing to do with inheritance or virtual methods. Following are examples of methods having different overloads: void area(int side);
  • 12. void area(int l, int b); void area(float radius); Practical example of Method Overloading (Compile Time Polymorphism) using System; namespacemethod_overloading { classProgram { publicclassPrint { publicvoid display(string name) { Console.WriteLine ("Your name is : " + name); } publicvoid display(int age, float marks) { Console.WriteLine ("Your age is : " + age); Console.WriteLine ("Your marks are :" + marks); } } staticvoid Main(string[] args)
  • 13. { Printobj = newPrint (); obj.display ("George"); obj.display (34, 76.50f); Console.ReadLine (); } } } Note:In the code if you observe display method is called two times. Display method will work according to the number of parameters and type of parameters. When and why to use method overloading Use method overloading in situation where you want a class to be able to do something, but there is more than one possibility for what information is supplied to the method that carries out the task. You should consider overloading a method when you for some reason need a couple of methods that take different parameters, but conceptually do the same thing. Method overloading showing many forms. using System; namespacemethod_overloading_polymorphism { ClassProgram
  • 14. { PublicclassShape { Publicvoid Area (float r) { float a = (float)3.14 * r; // here we have used function overload with 1 parameter. Console.WriteLine ("Area of a circle: {0}",a); } PublicvoidArea(float l, float b) { float x = (float)l* b; // here we have used function overload with 2 parameters. Console.WriteLine ("Area of a rectangle: {0}",x); } publicvoid Area(float a, float b, float c) { float s = (float)(a*b*c)/2; // here we have used function overload with 3 parameters. Console.WriteLine ("Area of a circle: {0}", s); } } Staticvoid Main (string[] args)
  • 15. { Shapeob = newShape (); ob.Area(2.0f); ob.Area(20.0f,30.0f); ob.Area(2.0f,3.0f,4.0f); Console.ReadLine (); } } } Things to keep in mind while method overloading If you use overload for method, there are couple of restrictions that the compiler imposes. The rule is that overloads must be different in their signature, which means the name and the number and type of parameters. There is no limit to how many overload of a method you can have. You simply declare them in a class, just as if they were different methods that happened to have the same name. Method Overriding: Whereas Overridingmeans changing the functionality of a method without changing the signature. We can override a function in base class by creating a similar function in derived class. This is done by using virtual/overridekeywords. Base class method has to be marked with virtual keyword and we can override it in derived class using override keyword. Derived class method will completely overrides base class method i.e. when we refer base class object created by casting derived class object a method in derived class will be called.
  • 16. Example: // Base class publicclassBaseClass { publicvirtualvoid Method1() { Console.Write("Base Class Method"); } } // Derived class publicclassDerivedClass : BaseClass { publicoverridevoid Method1() { Console.Write("Derived Class Method"); } } // Using base and derived class publicclassSample { publicvoidTestMethod() { // calling the overriden method DerivedClassobjDC = newDerivedClass(); objDC.Method1(); // calling the baesd class method BaseClassobjBC = (BaseClass)objDC; objDC.Method1(); } } Output --------------------- Derived Class Method Derived Class Method Constructors and Destructors: Classes have complicated internal structures, including data and functions, object initialization and cleanup for classes is much more complicated than it is for simple data structures. Constructors and destructors are special member functions of classes that are used to construct and destroy class objects. Construction may involve memory allocation and initialization for objects. Destruction may involve cleanup and deallocation of memory for objects.
  • 17. Constructors and destructors do not have return types nor can they return values. References and pointers cannot be used on constructors and destructors because their addresses cannot be taken. Constructors cannot be declared with the keyword virtual. Constructors and destructors cannot be declared const, or volatile. Unions cannot contain class objects that have constructors or destructors. Constructors and destructors obey the same access rules as member functions. For example, if you declare a constructor with protected access, only derived classes and friends can use it to create class objects. The compiler automatically calls constructors when defining class objects and calls destructors when class objects go out of scope. A constructor does not allocate memory for the class object it’s this pointer refers to, but may allocate storage for more objects than its class object refers to. If memory allocation is required for objects, constructors can explicitly call the new operator. During cleanup, a destructor may release objects allocated by the corresponding constructor. To release objects, use the delete operator. Example of Constructor classC { privateint x; privateint y; public C (int i, int j) { x = i; y = j; } publicvoid display () { Console.WriteLine(x + "i+" + y); } } Example of Destructor classD
  • 18. { public D () { // constructor } ~D () { // Destructor } }anoop and explain its principles in java? What is an oop and explain its principles in java? Answer: Java is an object oriented programming language. The main concepts used in Java are: Class Defines the abstract characteristics of a thing (object), including the thing's characteristics (its attributes, fields or properties) and the thing's behaviors (the things it can do, or methods, operations or features). One might say that a class is a blueprint or factory that describes the nature of something. For example, the class Dog would consist of traits shared by all dogs, such as breed and fur color (characteristics), and the ability to bark and sit (behaviors). Classes provide modularity and structure in an object-oriented computer program. A class should typically be recognizable to a non-programmer familiar with the problem domain, meaning that the characteristics of the class should make sense in context. Also, the code for a class should be relatively self-contained (generally using encapsulation). Collectively, the properties and methods defined by a class are called members. Object A pattern (exemplar) of a class. The class of Dog defines all possible dogs by listing the characteristics and behaviors they can have; the object Lassie is one particular dog, with particular versions of the characteristics. A Dog has fur; Lassie has brown-and-white fur. Instance One can have an instance of a class or a particular object. The instance is the actual object created at runtime. In programmer jargon, the Lassie object is an instance of the Dog class. The set of values of the attributes of a particular object is called its state. The object consists of state and the behaviour that's
  • 19. defined in the object's class. Method An object's abilities. In language, methods (sometimes referred to as "functions") are verbs. Lassie, being a Dog, has the ability to bark. So bark() is one of Lassie's methods. She may have other methods as well, for example sit() or eat() or walk() or save_timmy(). Within the program, using a method usually affects only one particular object; all Dogs can bark, but you need only one particular dog to do the barking. Message passing "The process by which an object sends data to another object or asks the other object to invoke a method."Also known to some programming languages as interfacing. For example, the object called Breeder may tell the Lassie object to sit by passing a "sit" message which invokes Lassie's "sit" method. The syntax varies between languages, for example: [Lassie sit] in Objective-C. In Java, code-level message passing corresponds to "method calling". Some dynamic languages use double-dispatch or multi-dispatch to find and pass messages. Inheritance "Subclasses" are more specialized versions of a class, which inherit attributes and behaviors from their parent classes, and can introduce their own. For example, the class Dog might have sub-classes called Collie, Chihuahua, and GoldenRetriever. In this case, Lassie would be an instance of the Collie subclass. Suppose the Dog class defines a method called bark() and a property called furColor. Each of its sub-classes (Collie, Chihuahua, and GoldenRetriever) will inherit these members, meaning that the programmer only needs to write the code for them once. Each subclass can alter its inherited traits. For example, the Collie class might specify that the default furColor for a collie is brown-and-white. The Chihuahua subclass might specify that the bark() method produces a high pitch by default. Subclasses can also add new members. The Chihuahua subclass could add a method called tremble(). So an individual chihuahua instance would use a high-pitched bark() from the Chihuahua subclass, which in turn inherited the usual bark() from Dog. The chihuahua object would also have the tremble() method, but Lassie would not, because she is a Collie, not a Chihuahua. In fact, inheritance is an "a... is a" relationship between classes, while instantiation is an "is a" relationship between an object and a class: a Collie is a Dog ("a... is a"), but Lassie is a Collie ("is a"). Thus, the object named Lassie has the methods from both classes Collie and Dog. Multiple inheritance is inheritance from more than one ancestor class, neither of these ancestors being an ancestor of the other. For example, independent classes could define Dogs and Cats, and a Chimera object could be created from these two which inherits all the (multiple) behavior of cats and dogs. This is not always supported, as it can be hard both to implement and to use well. Abstraction Abstraction is simplifying complex reality by modelling classes appropriate to the problem, and working at the most appropriate level of inheritance for a given aspect of the problem. For example, Lassie the Dog may be treated as a Dog much of the time, a Collie when necessary to
  • 20. access Collie-specific attributes or behaviors, and as an Animal (perhaps the parent class of Dog) when counting Timmy's pets. Abstraction is also achieved through Composition. For example, a class Car would be made up of an Engine, Gearbox, Steering objects, and many more components. To build the Car class, one does not need to know how the different components work internally, but only how to interface with them, i.e., send messages to them, receive messages from them, and perhaps make the different objects composing the class interact with each other. Encapsulation Encapsulation conceals the functional details of a class from objects that send messages to it. For example, the Dog class has a bark() method. The code for the bark() method defines exactly how a bark happens (e.g., by inhale() and then exhale(), at a particular pitch and volume). Timmy, Lassie's friend, however, does not need to know exactly how she barks. Encapsulation is achieved by specifying which classes may use the members of an object. The result is that each object exposes to any class a certain interface - those members accessible to that class. The reason for encapsulation is to prevent clients of an interface from depending on those parts of the implementation that are likely to change in future, thereby allowing those changes to be made more easily, that is, without changes to clients. For example, an interface can ensure that puppies can only be added to an object of the class Dog by code in that class. Members are often specified as public, protected or private, determining whether they are available to all classes, sub-classes or only the defining class. Some languages go further: Java uses the default access modifier to restrict access also to classes in the same package, C# and VB.NET reserve some members to classes in the same assembly using keywords internal (C#) or Friend (VB.NET), and Eiffel and C++ allow one to specify which classes may access any member. Polymorphism Polymorphism allows the programmer to treat derived class members just like their parent class' members. More precisely, Polymorphism in object-oriented programming is the ability of objects belonging to different data types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behavior. One method, or an operator such as +, -, or *, can be abstractly applied in many different situations. If a Dog is commanded to speak(), this may elicit a bark(). However, if a Pig is commanded to speak(), this may elicit an oink(). They both inherit speak() from Animal, but their derived class methods override the methods of the parent class; this is Overriding Polymorphism. Overloading Polymorphism is the use of one method signature, or one operator such as "+", to perform several different functions depending on the implementation. The "+" operator, for example, may be used to perform integer addition, float addition, list concatenation, or string concatenation. Any two subclasses of Number, such as Integer and Double, are expected to add together properly in an OOP language. The language must therefore overload the addition operator, "+", to work this way. This helps improve code readability. How this is implemented varies from language to language, but most OOP languages support at least some level of overloading polymorphism. Many OOP languages also support Parametric Polymorphism, where code is written without mention of any specific type and thus can be used transparently with any number of new types. Pointers are an example of a simple polymorphic routine that can be used with many different types of objects.
  • 21. Decoupling Decoupling allows for the separation of object interactions from classes and inheritance into distinct layers of abstraction. A common use of decoupling is to polymorphically decouple the encapsulation, which is the practice of using reusable code to prevent discrete code modules from interacting with each other. However, in practice decoupling often involves trade-offs with regard to which patterns of change to favor. The science of measuring these trade-offs in respect to actual change in an objective way is still in its infancy.