object oriented programmimg of java

Upload: babay321

Post on 03-Jun-2018

255 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/12/2019 Object Oriented Programmimg of Java

    1/27

    In this article we will discuss key concepts of object orientation with theirpractical implementation in C#. We will discuss here basics of OOPSincluding Interfaces, Access Modifiers, inheritance, polymorphism etc. his ismy second article on csharp!corner.com.

    My first article was "Memory Management in .$",you can find this article at http%&&www.c!sharpcorner.com&'pload(ile&tkagarwal&MemoryManagementInet))*+*-/0+*AM&MemoryManagementInet.asp1

    2ey Concepts of 3bject 3rientation

    Abstraction

    $ncapsulation

    4olymorphism

    Inheritance.

    Abstractionis the ability to generali5e an object as a data type that has aspecific set of characteristics and is able to perform a set of actions.

    3bject!oriented languages pro6ide abstraction 6ia classes. Classes define theproperties and methods of an object type.

    $1amples%

    7ou can create an abstraction of a dog with characteristics, such as

    color, height, and weight, and actions such as run and bite. hecharacteristics are called properties, and the actions are calledmethods.

    A 8ecordset object is an abstract representation of a set of data.

    Classes are blueprints for 3bject.3bjects are instance of classes.

    C# $1ample of Class%

    publicclass9raw:

    && Class code.;

    Object References

    http://www.c-sharpcorner.com/UploadFile/tkagarwal/MemoryManagementInNet11232005064832AM/MemoryManagementInNet.aspxhttp://www.c-sharpcorner.com/UploadFile/tkagarwal/MemoryManagementInNet11232005064832AM/MemoryManagementInNet.aspxhttp://www.c-sharpcorner.com/UploadFile/tkagarwal/MemoryManagementInNet11232005064832AM/MemoryManagementInNet.aspxhttp://www.c-sharpcorner.com/UploadFile/tkagarwal/MemoryManagementInNet11232005064832AM/MemoryManagementInNet.aspxhttp://www.c-sharpcorner.com/UploadFile/tkagarwal/MemoryManagementInNet11232005064832AM/MemoryManagementInNet.aspxhttp://www.c-sharpcorner.com/UploadFile/tkagarwal/MemoryManagementInNet11232005064832AM/MemoryManagementInNet.aspxhttp://www.c-sharpcorner.com/UploadFile/tkagarwal/MemoryManagementInNet11232005064832AM/MemoryManagementInNet.aspx
  • 8/12/2019 Object Oriented Programmimg of Java

    2/27

    When we work with an object we are using a reference to that object. 3n theother hand, when we are working with simple data types such as Integer, weare working with the actual 6alue rather than a reference.

    When we create a new object using the ew keyword, we store a reference

    to that object in a 6ariable. (or instance%

    9raw My9raw < new9raw=

    his code creates a new instance of 9raw. We gain access to this new object6ia the My9raw 6ariable. his 6ariable holds a reference to the object.

    ow we ha6e a second 6ariable, which also has a reference to that sameobject. We can use either 6ariable interchangeably, since they both referencethe e1act same object. he thing we need to remember is that the 6ariablewe ha6e is not the object itself but, rather, is just a reference or pointer to

    the object itself.

    Early bindingmeans that our code directly interacts with the object, bydirectly calling its methods. >ince the compiler knows the object?s data typeahead of time, it can directly compile code to in6oke the methods on theobject. $arly binding also allows the I9$ to use Intelli>ense to aid ourde6elopment efforts= it allows the compiler to ensure that we are referencingmethods that do e1ist and that we are pro6iding the proper parameter6alues.

    Late bindingmeans that our code interacts with an object dynamically atrun!time. his pro6ides a great deal of fle1ibility since our code literallydoesn?t care what type of object it is interacting with as long as the objectsupports the methods we want to call. @ecause the type of the object isn?tknown by the I9$ or compiler, neither Intelli>ense nor compile!time synta1checking is possible but we get unprecedented fle1ibility in e1change.

    If we enable strict type checking by using 3ption >trict 3n at the top of ourcode modules, then the I9$ and compiler will enforce early binding beha6ior.@y default, 3ption >trict is turned off and so we ha6e easy access to the useof late binding within our code.

    Access Modifiers

    Access Modifiers are keywords used to specify the declared accessibility of amember of a type.

  • 8/12/2019 Object Oriented Programmimg of Java

    3/27

    Publicis 6isible to e6eryone. A public member can be accessed using aninstance of a class, by a class?s internal code, and by any descendants of aclass.

    Privateis hidden and usable only by the class itself. o code using a classinstance can access a pri6ate member directly and neither can a descendantclass.

    Protectedmembers are similar to pri6ate ones in that they are accessibleonly by the containing class. owe6er, protected members also may be usedby a descendant class. >o members that are likely to be needed by adescendant class should be marked protected.

    Internal/Friend is public to the entire application but pri6ate to anyoutside applications. Internal is useful when you want to allow a class to beused by other applications but reser6e special functionality for theapplication that contains the class. Internal is used by C# and (riend byB@ .$.

  • 8/12/2019 Object Oriented Programmimg of Java

    4/27

    Protected Internal may be accessed only by a descendant class that?scontained in the same application as its base class. 7ou use protected

    internal in situations where you want to deny access to parts of a classfunctionality to any descendant classes found in other applications.

    Co!osition of an O"#EC$

    We use an interface to get access to an object?s data and beha6ior. heobject?s data and beha6iors are contained within the object, so a client

    application can treat the object like a black bo1 accessible only through itsinterface. his is a key object!oriented concept called $ncapsulation. heidea is that any programs that make use of this object won?t ha6e directaccess to the beha6iors or data!but rather those programs must make use ofour object?s interface.

    here are three main parts of 3bject%

  • 8/12/2019 Object Oriented Programmimg of Java

    5/27

    ). Interface*. Implementation or @eha6ior+. Member or Instance 6ariables

    Interface

    he interface is defined as a set of methods >ub and (unction routinesD,properties 4roperty routinesD, e6ents, and fields 6ariables or attributesDthat are declared 4ublic in scope.

    I!leentation or "e%avior

    he code inside of a method is called the implementation. >ometimes it isalso called beha6ior since it is this code that actually makes the object douseful work.Client applications can use our object e6en if we change the implementation!as long as we don?t change the interface. As long as our method name andits parameter list and return data type remain unchanged, we can changethe implementation all we want.

    >o Method >ignature depends on%

    Method name

    9ata types of parameters

    $ither 4arameter is passed @yBal or @y8ef.

    8eturn type of method.

    It is important to keep in mind that encapsulation is a syntactic tool!it allowsour code to continue to run without change. owe6er, it is not semantic!meaning that, just because our code continues to run, doesn?t mean itcontinues to do what we actually wanted it to do.

    Meber or Instance &ariables

    he third key part of an object is its data, or state. $6ery instance of a class

    is absolutely identical in terms of its interface and its implementation!theonly thing that can 6ary at all is the data contained within that particularobject.

    Member 6ariables are those declared so that they are a6ailable to all codewithin our class. ypically member 6ariables are 4ri6ate in scope!a6ailableonly to the code in our class itself. hey are also sometimes referred to asinstance 6ariables or as attributes. he .$ (ramework also refers to them

  • 8/12/2019 Object Oriented Programmimg of Java

    6/27

    as fields.We shouldn?t confuse instance 6ariables with properties. A 4roperty is a typeof method that is geared around retrie6ing and setting 6alues, while aninstance 6ariable is a 6ariable within the class that may hold the 6aluee1posed by a 4roperty.

    Interface looks like a class, but has no implementation.

    he only thing it contains is definitions of e6ents, inde1ers, methods and&orproperties. he reason interfaces only pro6ide definitions is because they areinherited by classes and structs, which must pro6ide an implementation foreach interface member defined. >o, what are interfaces good for if theydon?t implement functionalityE hey?re great for putting together plug!n!playlike architectures where components can be interchanged at will. >ince allinterchangeable components implement the same interface, they can beused without any e1tra programming. he interface forces each componentto e1pose specific public members that will be used in a certain way.

    @ecause interfaces must be defined by inheriting classes and structs, theydefine a contract. (or instance, if class foo inherits from the I9isposableinterface, it is making a statement that it guarantees it has the 9isposeDmethod, which is the only member of the I9isposable interface. Any codethat wishes to use class foo may check to see if class foo inheritsI9isposable. When the answer is true, then the code knows that it can callfoo.9isposeD.

    9efining an Interface% MyInterface.c

    interfaceIMyInterface:

    6oidMethodoImplementD=;

    Abo6e listing shows defines an interface named IMyInterface. A commonnaming con6ention is to prefi1 all interface names with a capital "I", but thisis not mandatory. his interface has a single method namedMethodoImplementD. his could ha6e been any type of method declaration

    with different parameters and return types. otice that this method does notha6e an implementation instructions between curly braces! :;D, but insteadends with a semi!colon, "=". his is because the interface only specifies thesignature of methods that an inheriting class or struct must implement.

    All the methods of Interface are public by default and no access modifierslike pri6ate, publicD are allowed with any method of Interface.

  • 8/12/2019 Object Oriented Programmimg of Java

    7/27

    'sing an Interface% InterfaceImplementer.cs

    classInterfaceImplementer % IMyInterface:

    public6oidMethodoImplementD:

    Console.WriteFine"MethodoImplementD called."D=;

    ;

    he InterfaceImplementer class in abo6e listing implements the IMyInterfaceinterface. Indicating that a class inherits an interface is the same asinheriting a class. In this case, the following synta1 is used%

    classInterfaceImplementer % IMyInterface

    ote that this class inherits the IMyInterface interface= it must implement its

    all members. While implementing interface methods all those needs to bedeclared public only. It does this by implementing the MethodoImplementDmethod. otice that this method implementation has the e1act samesignature, parameters and method name, as defined in the IMyInterfaceinterface. Any difference will cause a compiler error. Interfaces may alsoinherit other interfaces. (ollowing listing shows how inherited interfaces areimplemented.

    Interface Inheritance% InterfaceInheritance.cs

    using>ystem=

    interfaceI4arentInterface:

    6oid4arentInterfaceMethodD=;

    interfaceIMyInterface % I4arentInterface:

    6oidMethodoImplementD=;

    classInterfaceImplementer % IMyInterface:

    public6oidMethodoImplementD:

    Console.WriteFine"MethodoImplementD called."D=

    ;public6oid4arentInterfaceMethodD:

    Console.WriteFine"4arentInterfaceMethodD called."D=

    ;;

    he code in abo6e listing contains two interfaces% IMyInterface and theinterface it inherits, I4arentInterface. When one interface inherits another,

  • 8/12/2019 Object Oriented Programmimg of Java

    8/27

    any implementing class or struct must implement e6ery interface member inthe entire inheritance chain. >ince the InterfaceImplementer class in abo6elisting inherits from IMyInterface, it also inherits I4arentInterface. herefore,the InterfaceImplementer class must implement the MethodoImplementDmethod specified in the IMyInterface interface and the

    4arentInterfaceMethodD method specified in the I4arentInterface interface.

    In summary, you can implement an interface and use it in a class. Interfacesmay also be inherited by other interface. Any class or struct that inherits aninterface must also implement all members in the entire interfaceinheritance chain.

    In%eritanceis the idea that one class, called a subclass, can be based onanother class, called a base class. Inheritance pro6ides a mechanism forcreating hierarchies of objects.

    Inheritance is the ability to apply another class?s interface and code to yourown class.

    ormal base classes may be instantiated themsel6es, or inherited. 9eri6edclasses can inherit base class members marked with protected or greateraccess. he deri6ed class is speciali5ed to pro6ide more functionality, inaddition to what its base class pro6ides. Inheriting base class members inderi6ed class is not mandatory.

    Access 'ey(ords

    base !G Access the members of the base class.this !G 8efer to the current object for which a method is called.

    he base keyword is used to access members of the base class from within aderi6ed class%Call a method on the base class that has been o6erridden by anothermethod. >pecify which base!class constructor should be called when creatinginstances of the deri6ed class. A base class access is permitted only in aconstructor, an instance method, or an instance property accessor.

    In following e1ample, both the base class, 4erson, and the deri6ed class,$mployee, ha6e a method named Hetinfo. @y using the base keyword, it ispossible to call the Hetinfo method on the base class, from within thederi6ed class.

    && Accessing base class members

    using>ystem=

  • 8/12/2019 Object Oriented Programmimg of Java

    9/27

    publicclass4erson:

    protectedstringssn < "///!--!"=protectedstringname < "ohn F. Malgraine"=

    public6irtual6oidHetInfoD:

    Console.WriteFine"ame% :;", nameD=Console.WriteFine">>% :;", ssnD=

    ;;

    class$mployee% 4erson:

    publicstringid < "A@C-J$(H"=publico6erride6oidHetInfoD

    :&& Calling the base class HetInfo method%

    base.HetInfoD=

    Console.WriteFine"$mployee I9% :;", idD=;

    ;classestClass:

    publicstatic6oidMainD:

    $mployee $ < new$mployeeD=$.HetInfoD=

    ;

    ;

    3utputame% ohn F. Malgraine>>% ///!--!$mployee I9% A@C-J$(H

    @ase class constructors can be called from deri6ed classes. o call a baseclass constructor, use the baseD constructor reference. his is desirablewhen it?s necessary to initiali5e a base class appropriately.

    ere?s an e1ample that shows the deri6ed class constructor with an addressparameter%

    abstractpublicclassContact:

    pri6atestringaddress=publicContactstringbKaddressD

    :this.address < bKaddress=

    ;;

    publicclassCustomer % Contact

  • 8/12/2019 Object Oriented Programmimg of Java

    10/27

    :publicCustomerstringcKaddressD % baseCKaddressD

    :;

    ;

    In this code, the Customer class does not ha6e an address, so it passes theparameter to its base class constructor by adding a colon and the basekeyword with the parameter to its declaration. his calls the Contactconstructor with the address parameter, where the address field in Contact isinitiali5ed.

    3ne more e1ample which shows how base!class constructor is called whencreating instances of a deri6ed class%

    using>ystem=publicclassMy@ase

    :intnum=

    publicMy@aseD:

    Console.WriteFine"In My@aseD"D=;

    publicMy@aseintiD:

    num < i=Console.WriteFine"in My@aseint iD"D=

    ;

    publicintHetumD:

    returnnum=

    ;;

    publicclassMy9eri6ed % My@ase:

    staticinti < +*=&& his constructor will call [email protected]@aseD

    publicMy9eri6edintiiD % baseD:

    ;&& his constructor will call [email protected]@aseint iD

    publicMy9eri6edD % baseiD

    :;publicstatic6oidMainD

    :My9eri6ed md < newMy9eri6edD=&& calls public My9eri6edD % baseiD and

    && passes i

  • 8/12/2019 Object Oriented Programmimg of Java

    11/27

    3utputin My@aseint iDin My@aseD

    he following e1ample will not compile. It illustrates the effects of notincluding a default constructor in a class definition%

    abstractpublicclassContact:

    pri6atestringaddress=publicContactstringaddressD

    :this.address < address=

    ;;

    publicclassCustomer % Contact:

    publicCustomerstringaddressD

    :;

    ;

    In this e1ample, the Customer constructor does not call the base classconstructor. his is ob6iously a bug, since the address field will ne6er beinitiali5ed.

    When a class has no e1plicit constructor, the system assigns a defaultconstructor. he default constructor automatically calls a default or

    parameterless base constructor. ere?s an e1ample of automatic defaultconstructor generation that would occur for the preceding e1ample%

    publicCustomerD % ContactD

    :;

    When a class does not declare any constructors, the code in this e1ample isautomatically generated. he default base class constructor is calledimplicitly when no deri6ed class constructors are defined. 3nce a deri6edclass constructor is defined, whether or not it has parameters, a default

    constructor will not be automatically defined, as the preceding code showed.

    Calling "ase Class Mebers

    9eri6ed classes can access the members of their base class if thosemembers ha6e protected or greater access. >imply use the member name in

  • 8/12/2019 Object Oriented Programmimg of Java

    12/27

    the appropriate conte1t, just as if that member were a part of the deri6edclass itself. ere?s an e1ample%

    abstractpublicclassContact:

    pri6atestringaddress=pri6atestringcity=

    pri6atestringstate=pri6atestring5ip=

    publicstring(ullAddressD

    :stringfullAddress < address L ?n? L city L ?,? L state L ? ? L 5ip=

    returnfullAddress=

    ;;

    publicclassCustomer % Contact:

    publicstringHenerate8eportD

    :stringfullAddress < (ullAddressD=

    && do some other stuff...

    returnfullAddress=;

    ;

    In abo6e e1ample, the Henerate8eportD method of the Customer class callsthe (ullAddressD method in its base class, Contact. All classes ha6e fullaccess to their own members without Nualification. Oualification refers tousing a class name with the dot operator to access a class member!My3bject.>omeMethodD, for instance. his shows that a deri6ed class canaccess its base class members in the same manner as its own.

    More ips regarding Inheritance%

    A static member cannot be marked as o6erride, 6irtual, or abstract. >o

    following is an error%public static 6irtual 6oid Het>>D

    7ou can?t call static methods of base class from deri6ed class using

    base keyword.In abo6e e1ample if you declare a static method as follows%

    publicclass4erson:

    protectedstringssn < "///!--!"=protectedstringname < "ohn F. Malgraine"=

    publicstatic6oidHetInfoD:

    && Implementation

  • 8/12/2019 Object Oriented Programmimg of Java

    13/27

    ;;

    now you can?t call this method using base.HetInfoD from deri6ed classinstead you ha6e to call 4erson.HetInfoD from deri6ed class.

    Inside >tatic members we can access only static fields, methods etc.(ollowing e1ample will gi6e error, because we can?t access name in HetInfoDbecause name is not static.

    publicclass4erson

    :protectedstringssn < "///!--!"=

    protectedstringname < "ohn F. Malgraine"=publicstatic6oidHetInfoD

    :

    Console.WriteFine"ame% :;", nameD=

    Console.WriteFine">>% :;", ssnD=;;

    Birtual or abstract members cannot be pri6ate.

    If you are not o6erriding a 6irtual method of base class in deri6ed

    class, you can?t use base class method by using base keyword inderi6ed class. Also when you will create an instance of deri6ed class, itwill call deri6ed class method and you will only be able to access baseclass method when you will create instance of base class.

    7ou can?t decrease access le6el of a method in deri6ed class when youare o6erriding a base class method in deri6ed class, 6ice 6ersa ispossible.Means you can make protected method of base class to public inderi6ed class.

    he "this" keyword refers to%

    the current instance for which a method is called. >tatic member

    functions do not ha6e a this pointer. he this keyword can be used toaccess members from within constructors, instance methods, and

    instance accessors.he following are common uses of this%

    o Nualify members hidden by similar names, for e1ample%

    public$mployeestringname, stringaliasD

    :this.name < name=

  • 8/12/2019 Object Oriented Programmimg of Java

    14/27

    this.alias < alias=;

    In abo6e e1ample, this.name refers to pri6ate 6ariable name in the class. Ifwe write name < name, then this will refer to argument name of theconstructor $mployee and not to pri6ate 6ariable name in the class. In thiscase pri6ate 6ariable name will ne6er be initiali5ed.

    o pass an object as a parameter to other methods, for e1ample%

    Calca1thisD=

    o declare inde1ers, for e1ample%

    publicintthisPintparamQ

    :get

    :

    returnarrayPparamQ=;set

    :arrayPparamQ < 6alue=

    ;;

    It is an error to refer to this in a static method, static property accessor, or6ariable initiali5er of a field declaration.

    In this e1ample, this is used to Nualify the $mployee class members, nameand alias, which are hidden by similar names. It is also used to pass anobject to the method Calca1, which belongs to another class.

    && keywordsKthis.cs

    && this e1ampleusing>ystem=

    publicclass$mployee

    :publicstringname=

    publicstringalias=

    publicdecimalsalary < +.m=&& Constructor%

    public$mployeestringname, stringaliasD:

    && 'se this to Nualify the fields, name and alias%this.name < name=

    this.alias < alias=;

    && 4rinting method%public6oidprint$mployeeD

    :

  • 8/12/2019 Object Oriented Programmimg of Java

    15/27

    Console.WriteFine"ame% :;nAlias% :);", name, aliasD=&& 4assing the object to the Calca1 method by using this%

    Console.WriteFine"a1es% :%C;", a1.Calca1thisDD=;

    ;publicclassa1

    :publicstaticdecimalCalca1$mployee $D

    :return.0mR$.salaryDD=

    ;;

    publicclassMainClass:

    publicstatic6oidMainD:

    && Create objects%

    $mployee $) < new$mployee "ohn M. rainer", "jtrainer"D=&& 9isplay results%

    $).print$mployeeD=;;

    3utputame% ohn M. rainerAlias% jtrainera1es% S*/.

    Abstract Classes

    Abstract classes are a special type of base classes. In addition to normalclass members, they ha6e abstract class members. hese Abstract classmembers are methods and properties that are declared without animplementation. All classes deri6ed directly from abstract classes mustimplement all of these abstract methods and properties.

    Abstract classes can ne6er be instantiated. his would be illogical, becauseof the members without implementations.>o what good is a class that can?tbe instantiatedE FotsT Abstract classes sit toward the top of a class hierarchy.hey establish structure and meaning to code. hey make frameworks easier

    to build. his is possible because abstract classes ha6e information andbeha6ior common to all deri6ed classes in a framework. ake a look at thefollowing e1ample%

    abstractpublicclassContact&& Abstract Class Contact.:

    protectedstringname=

    publicContactD:

  • 8/12/2019 Object Oriented Programmimg of Java

    16/27

    && statements...;

    publicabstract6oidgenerate8eportD=abstractpublicstringame

    :get=

    set=;

    ;

    Contact, is an abstract class. Contact has two abstract members, and it hasan abstract method named generate8eportD. his method is declared withthe abstract modifier in front of the method declaration. It has noimplementation no bracesD and is terminated with a semicolon. he ameproperty is also declared abstract. he accessors of properties areterminated with semicolons.

    publicclassCustomer % Contact&& Customer Inherits Abstract Class Contact.:

    stringgender=decimalincome=

    intnumber3fBisits=publicCustomerD

    :&& statements

    ;publico6erride6oidgenerate8eportD

    :&& uniNue report

    ;

    publico6erridestringame:

    get:

    number3fBisitsLL=

    returnname=;

    set:

    name < 6alue=number3fBisits < =

    ;;

    ;publicclass>ite3wner % Contact

    :intsiteits=

    stringmy>ite=public>ite3wnerD

    :&& statements

  • 8/12/2019 Object Oriented Programmimg of Java

    17/27

    ;publico6erride6oidgenerate8eportD

    :&& uniNue report

    ;publico6erridestringame

    :get

    :siteitsLL=

    returnname=;

    set:

    name < 6alue=siteits < =

    ;

    ;;

    he abstract base class Contact has two deri6ed classes, Customer and>ite3wner. @oth of these deri6ed classes implement the abstract members ofthe Contact class. he generate8eportD method in each deri6ed class has ano6erride modifier in its declaration. Fikewise, the ame declaration containsan o6erride modifier in both Customer and >ite3wner.

    C# reNuires e1plicit declaration of intent when o6erriding methods. hisfeature promotes safe code by a6oiding the accidental o6erriding of baseclass methods, which is what actually does happen in other languages.

    Fea6ing out the o6erride modifier generates an error. >imilarly, adding a newmodifier also generates an error. Abstract methods must be o6erridden andcannot be hidden, which the new modifier or the lack of a modifier would betrying to do.

    he most famous of all abstract classes is the 3bject class. It may bereferred to as object or 3bject, but it?s still the same class. 3bject is thebase class for all other classes in C#. It?s also the default base class when abase class is not specified. he following class declarations produce the samee1act results%

    abstractpublicclassContact % 3bject:

    && class members;

    abstractpublicclassContact:

    && class members;

  • 8/12/2019 Object Oriented Programmimg of Java

    18/27

    3bject is implicitly included as a base class if it is not already declared.@esides pro6iding the abstract glue to hold together the C# class framework,object includes built!in functionality, some of which is useful for deri6edclasses to implement.

    )ifference bet(een Interface and Abstract Class

    Interfaces are closely related to abstract classes that ha6e all members

    abstract. (or an abstract class, at least one method of the class must be an

    abstract method that means it may ha6e concrete methods.

    (or an interface, all the methods must be abstract

    Class that implements an interface much pro6ide concrete

    implementation of all the methods definition in an interface or else

    must be declare an abstract class

    In C#, multiple inheritance is possible only through implementation of

    multiple interfaces. Abstract class can only be deri6ed once.

    An interface defines a contract and can only contains four entities 6i5

    methods, properties, e6ents and inde1es. An interface thus cannotcontain constants, fields, operators, constructors, destructors, staticconstructors, or types.

    Also an interface cannot contain static members of any kind. he

    modifiers abstract, public, protected, internal, pri6ate, 6irtual, o6errideis disallowed, as they make no sense in this conte1t.

    Class members that implement the interface members must be

    publicly accessible.

    Overriding Suery*

    A deri6ed class may o6erride a 6irtual method of the base class with thekeyword o6erride. he following restrictions must be followed.

    2eyword o6erride is used in the definition of child class method that isgoing to o6erride the base class?s 6irtual method.

    he return type must be the same as the 6irtual method ha6e in base

    class.

    he name of the method should also be same.

  • 8/12/2019 Object Oriented Programmimg of Java

    19/27

    he parameter!list must also be same in order, number and type of

    parameters.

    he accessibility of the o6erriding method should not be more

    restricted than that of the accessibility defined with 6irtual method of

    the base class. his accessibility either be the same or less restricted.

    he 6irtual methods can be sealed in the child or deri6ed classes to

    pre6ent further modifications in the implementation of the 6irtualmethod in the deri6ed classes, by declaring them as sealed methods.

    +iding "ase Class Mebers

    >ometimes deri6ed class members ha6e the same name as a correspondingbase class member. In this case, the deri6ed member is said to be "hiding"the base class member.

    When hiding occurs, the deri6ed member is masking the functionality of thebase class member. 'sers of the deri6ed class won?t be able to see thehidden member= they?ll see only the deri6ed class member. he followingcode shows how hiding a base class member works.

    abstractpublicclassContact:

    pri6atestringaddress=pri6atestringcity=

    pri6atestringstate=pri6atestring5ip=

    publicstring(ullAddressD:stringfullAddress ite3wner % Contact:

    publicstring(ullAddressD:

    stringfullAddress=&& create an address...

    returnfullAddress=;

    ;

    In this e1ample, both >ite3wner and its base class, Contact, ha6e a methodnamed (ullAddressD. he (ullAddressD method in the >ite3wner class hidesthe (ullAddressD method in the Contact class. his means that when aninstance of a >ite3wner class is in6oked with a call to the (ullAddressD

  • 8/12/2019 Object Oriented Programmimg of Java

    20/27

    method, it is the >ite3wner class (ullAddressD method that is called, not the(ullAddressD method of the Contact class.

    Although a base class member may be hidden, the deri6ed class can stillaccess it. It does this through the base identifier. >ometimes this is

    desirable. It is often useful to take ad6antage of the base class functionalityand then add to it with the deri6ed class code. he ne1t e1ample shows howto refer to a base class method from the deri6ed class.

    abstractpublicclassContact:

    pri6atestringaddress=

    pri6atestringcity=pri6atestringstate=

    pri6atestring5ip=

    publicstring(ullAddressD:

    stringfullAddress ite3wner % Contact:

    publicstring(ullAddressD:

    stringfullAddress < base.(ullAddressD=&& do some other stuff...

    returnfullAddress=;

    ;

    In this particular e1ample, the (ullAddressD method of the Contact class iscalled from within the (ullAddressD method of the >ite3wner class. his isaccomplished with a base class reference. his pro6ides another way toreuse code and add on to it with customi5ed beha6ior.

    &ersioning

    Bersioning, in the conte1t of inheritance, is a C# mechanism that allowsmodification of classes creating new 6ersionsD without accidentally changing

    the meaning of the code. iding a base class member with the methodspre6iously described generates a warning message from the compiler. his isbecause of the C# 6ersioning policy. It?s designed to eliminate a class ofproblems associated with modifications to base classes.

    ere?s the scenario% A de6eloper creates a class that inherits from a third!party library. (or the purposes of this discussion, we assume that theContact class represents the third!party library. ere?s the e1ample%

  • 8/12/2019 Object Oriented Programmimg of Java

    21/27

    publicclassContact:

    && does not include (ullAddressD method;

    publicclass>ite3wner % Contact:

    publicstring(ullAddressD:

    stringfullAddress < my>ite.o>tringD=returnfullAddress=

    ;;

    In this e1ample, the (ullAddressD method does not e1ist in the base class.here is no problem yet. Fater on, the creators of the third!party libraryupdate their code. 4art of this update includes a new member in a base classwith the e1act same name as the deri6ed class%

    publicclassContact:pri6atestringaddress=

    pri6atestringcity=pri6atestringstate=

    pri6atestring5ip=publicstring(ullAddressD

    :stringfullAddress ite3wner % Contact:publicstring(ullAddressD

    :

    stringfullAddress < my>ite.o>tringD=returnfullAddress=

    ;

    ;

    In this code, the base class method (ullAddressD contains differentfunctionality than the deri6ed class method. In other languages, thisscenario would break the code because of implicit polymorphism. owe6er,

    this does not break any code in C# because when the (ullAddressD methodis called on >ite3wner, it is still the >ite3wner class method that gets called.

    his scenario generates a warning message. 3ne way to eliminate thewarning message is to place a new modifier in front of the deri6ed classmethod name, as the following e1ample shows%

  • 8/12/2019 Object Oriented Programmimg of Java

    22/27

    using>ystem=publicclassWeb>ite

    :publicstring>iteame=

    publicstring'8F=publicstring9escription=

    publicWeb>iteD:

    ;publicWeb>ite stringstr>iteame, stringstr'8F, stringstr9escription D

    :>iteame < str>iteame=

    '8F < str'8F=9escription < str9escription=

    ;publico6erridestringo>tringD

    :

    return>iteame L ", " L'8F L ", " L9escription=;

    ;publicclassContact:

    publicstringaddress=publicstringcity=

    publicstringstate=publicstring5ip=

    publicstring(ullAddressD:

    stringfullAddress ite3wner % Contact:

    intsiteits=stringname=

    Web>ite my>ite=public>ite3wnerD

    :my>ite < newWeb>iteD=

    siteits < =;

    public>ite3wnerstringaame, Web>ite a>iteD

    :

    my>ite < newWeb>itea>ite.>iteame,a>ite.'8F,a>ite.9escriptionD=ame < aame=

    ;newpublicstring(ullAddressD

    :stringfullAddress < my>ite.o>tringD=

    returnfullAddress=;

    publicstringame

  • 8/12/2019 Object Oriented Programmimg of Java

    23/27

    :get

    :siteitsLL=

    returnname=;

    set:

    name < 6alue=siteits < =

    ;;

    ;publicclassest

    :publicstatic6oidMainD

    :

    Web>ite my>ite < newWeb>ite"Fe (inancier","http%&&www.Fe(inancier.com","(ancy(inancial >ite"D=

    >ite3wner an3wner < new>ite3wner"ohn 9oe", my>iteD=stringaddress=an3wner.address < ")*+ Fane Fane"=

    an3wner.city < ">ome own"=an3wner.state < "I"=

    an3wner.5ip < "/-J0"=address < an3wner.(ullAddressD=&& 9ifferent 8esults

    Console.WriteFine"Address% n:;n", addressD=;

    ;

    ere?s the output%

    Address%Fe (inancier, http%&&www.Fe(inancier.com, (ancy (inancial >ite

    his has the effect of e1plicitly letting the compiler know the de6eloper?sintent. 4lacing the new modifier in front of the deri6ed class member statesthat the de6elopers know there is a base class method with the same name,and they definitely want to hide that member. his pre6ents breakage ofe1isting code that depends on the implementation of the deri6ed classmember. With C#, the method in the deri6ed class is called when an objectof the deri6ed class type is used. Fikewise, the method in the base class iscalled when an object of the @ase class type is called. Another problem thispresents is that the base class may present some desirable new featuresthat wouldn?t be a6ailable through the deri6ed class.

    o use these new features reNuires one of a few different workarounds. 3neoption would be to rename the deri6ed class member, which would allowprograms to use a base class method through a deri6ed class member. hedrawback to this option would be if there were other classes relying upon the

    http://www.lefinancier.com/http://www.lefinancier.com/
  • 8/12/2019 Object Oriented Programmimg of Java

    24/27

    implementation of the deri6ed class member with the same name. hisscenario will break code and, for this reason, is considered e1tremely badform.

    Another option is to define a new method in the deri6ed class that called the

    base class method. his allows users of the deri6ed class to ha6e the newfunctionality of the base class, yet retain their e1isting functionality with thederi6ed class. While this would work, there are maintainability concerns forthe deri6ed class.

    Sealed Classes

    >ealed classes are classes that can?t be deri6ed from. o pre6ent otherclasses from inheriting from a class, make it a sealed class. here are acouple good reasons to create sealed classes, including optimi5ation andsecurity.

    >ealing a class a6oids the system o6erhead associated with 6irtual methods.his allows the compiler to perform certain optimi5ations that are otherwiseuna6ailable with normal classes.

    Another good reason to seal a class is for security. Inheritance, by its 6erynature, dictates a certain amount of protected access to the internals of apotential base class. >ealing a class does away with the possibility ofcorruption by deri6ed classes. A good e1ample of a sealed class is the >tringclass. he following e1ample shows how to create a sealed class%

    publicsealedclassCustomer>tats:

    stringgender=decimalincome=

    intnumber3fBisits=

    publicCustomer>tatsD:

    ;

    ;publicclassCustomerInfo % Customer>tats&& error

    :;

    his e1ample generates a compiler error. >ince the Customer>tats class issealed, it can?t be inherited by the CustomerInfo class.he Customer>tatsclass was meant to be used as an encapsulated object in another class. hisis shown by the declaration of a Customer>tats object in the Customer class.

    publicclassCustomer

    :

  • 8/12/2019 Object Oriented Programmimg of Java

    25/27

    Customer>tats my>tats=&& okay;

    Polyor!%is

    4olymorphism is reflected in the ability to write one routine that can operateon objects from more than one class!treating different objects from differentclasses in e1actly the same way. (or instance, if both Customer and Bendorobjects ha6e a ame property, and we can write a routine that calls theame property regardless of whether we?re using a Customer or Bendorobject, then we ha6e polymorphism.

    A 6ehicle is a good e1ample of polymorphism. A 6ehicle interface would onlyha6e those properties and methods that all 6ehicles ha6e, a few of whichmight include paint color, number of doors, accelerator, and ignition. heseproperties and methods would apply to all types of 6ehicles including cars,

    trucks, and semi!trucks.

    4olymorphism will not implement code behind the 6ehicle?s properties andmethods. Instead, polymorphism is the implementation of an interface. Ifthe car, truck, and semitruck all implement the same 6ehicle interface, thenthe client code for all three classes can be e1actly the same.

    C# gi6es us polymorphism through inheritance. C# pro6ides a keyword6irtual that is used in the definition of a method to support polymorphism.

    Child class are now free to pro6ide their own implementation of this 6irtualmethod, that is called o6erriding. he following points are importantregarding 6irtual keyword%!

    If the method is not 6irtual, the compiler simply uses the reference type toin6oke the appropriate method.

    If the method is 6irtual, the compiler will generate code to checkup thereference type at runtime it is actually denoting to, then the appropriatemethod is called from the class of the reference type.

    When a 6irtual method is called, runtime check late method bindingD ismade to identify the object and appropriate method is in6oked, all this isdone at runtime.

    In case of non!6irtual methods, this information is a6ailable at compile time,so no runtime check to identify the object is made, so slightly efficient in theway non!6irtual methods are called. @ut the beha6ior of 6irtual method is

  • 8/12/2019 Object Oriented Programmimg of Java

    26/27

    useful in many ways= the functionality they pro6ide is fair enough to bearthis slight loss of performance.

    I!leenting Polyor!%is

    he key factor here is the ability to dynamically in6oke methods in a classbased on their type. $ssentially, a program would ha6e a group of objects,e1amine the type of each one, and e1ecute the appropriate method. ere?san e1ample%

    using>ystem=publicclassWeb>ite

    :publicstring>iteame=

    publicstring'8F=publicstring9escription=

    publicWeb>iteD

    :;publicWeb>ite stringstr>iteame, stringstr'8F, stringstr9escription D

    :>iteame < str>iteame=

    '8F < str'8F=9escription < str9escription=

    ;

    publico6erridestringo>tringD:

    return>iteame L ", " L'8F L ", " L9escription=

    ;

    ;

    When we inherit abo6e class, we ha6e two choices to in6oke constructor ofthe class. >o this is an e1ample of design time polymorphism. ere at designtime we ha6e to decide which method we need to in6oke while inheriting theclass.

    4olymorphism is the capability of a program to carry out dynamic operationsby implementing methods of multiple deri6ed classes through a commonbase class reference. Another definition of polymorphism is the ability totreat different objects the same way. his means that the runtime type of an

    object determines its beha6ior rather than the compile!time type of itsreference.

    Suery*

    It was a long trip, but I tried to e1plain all the basics of 3bject 3rientation inC# with some practical e1amples. If you are interested to read my pre6iousarticle "Memory management in .$", you can find it at%

  • 8/12/2019 Object Oriented Programmimg of Java

    27/27

    http://www.c-

    sharpcorner.com/UploadFile/tkagarwal/MemoryManagementInNet11232!"#$32%M/Memor

    yManagementInNet.asp&

    http://www.c-sharpcorner.com/UploadFile/tkagarwal/MemoryManagementInNet11232005064832AM/MemoryManagementInNet.aspxhttp://www.c-sharpcorner.com/UploadFile/tkagarwal/MemoryManagementInNet11232005064832AM/MemoryManagementInNet.aspxhttp://www.c-sharpcorner.com/UploadFile/tkagarwal/MemoryManagementInNet11232005064832AM/MemoryManagementInNet.aspxhttp://www.c-sharpcorner.com/UploadFile/tkagarwal/MemoryManagementInNet11232005064832AM/MemoryManagementInNet.aspxhttp://www.c-sharpcorner.com/UploadFile/tkagarwal/MemoryManagementInNet11232005064832AM/MemoryManagementInNet.aspxhttp://www.c-sharpcorner.com/UploadFile/tkagarwal/MemoryManagementInNet11232005064832AM/MemoryManagementInNet.aspx