Ganesh groups


Published on

java inheritence concept

Published in: Education, Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Ganesh groups

  1. 1. Inheritance and Its typesReusabilityInheritanceRe-usability is yet another imperative attribute of OOP. It is always fine if we could reusesomething that already exists rather than construct it again. It helps in saving time and money. Italso avoids the frustration and increase the reliability. Fortunately, C++ powerfully supports theconception of reusability. The C++ classes can be reused in numerous ways. Once a class haswritten 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 asclass composition again. For example, classes A contains two-member function ads and subtractsand class b contain two different functions multiply and divide. We want to use all these functionwith 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 followingtypes of inheritance:1. Single class Inheritance:Single Class InheritanceThe derived class inherits some or all of the traits from the base class. A class can also inheritproperties from more than one class or from more than one level. A derived class with only one
  2. 2. base case is celled single inheritance. When class A has inherited in class has known as baseclass and B class is know as derived class. Here only two classes have connected to each other.2. Multilevel Inheritance:Multilevel InheritanceIn this type of inheritance, there are number of level and it has used in that cases where we wantto use all properties in number of levels according to the requirement. It is not unusual that aclass is derived from another derived class. The class a serves as a base class for the derivedclass B, which in turn serves as a base class for the derived class C. The class B is known asintermediary 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 startingpoint for defining new classes. It is like a child inheriting the physical features of one parent andthe brainpower of another.4. Hierarchical Inheritance:
  3. 3. Hierarchical Inheritance:This type of inheritance helps us to generate a baseless for number of classes and those numbersof 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 canproduce an error of using same name function from no of classes, which will bother the compilerto how to use the functions. Therefore, it will generate errors in the program. This has known asambiguity oJava Final Keyword22/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. 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 classC# is a complete object oriented programming language. Inheritance is one of the primaryconcepts of object-oriented programming. It allows you to reuse existing code. Througheffective use of inheritance, you can save lot of time in your programming and also reduceerrors, which in turn will increase the quality of work and productivity. A simple example tounderstand inheritance in C#.Using System;PublicclassBaseClass{ PublicBaseClass () { Console.WriteLine ("Base Class Constructor executed"); }
  5. 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 thewrite () method. If you observe the ChildClass does not have a write() method in it. Thiswrite () method has been inherited from the parent BaseClass.The output of the above program isOutput:
  6. 6. Base Class Constructor executed Child Class Constructor executed Write method in Base Class executedthis output proves that when we create an instance of a child class, the base classconstructor will automatically be called before the child class constructor. So in general Baseclasses are automatically instantiated before derived classes.In C# the syntax for specifying BaseClass and ChildClass relationship is shown below. Thebase class is specified by adding a colon, ":", after the derived class identifier and thenspecifying the base class name.Syntax: class ChildClassName: BaseClass { //Body }C# supports single class inheritance only. What this means is, your class can inherit fromonly one base class at a time. In the code snippet below, class C is trying to inherit fromClass A and B at the same time. This is not allowed in C#. This will lead to a compile timeerror: Class C cannot have multiple base classes: A and B.publicclassA{}publicclassB{}publicclassC : A, B{}
  7. 7. In C# Multi-Level inheritance is possible. Code snippet below demonstrates mlti-levelinheritance. Class B is derived from Class A. Class C is derived from Class B. So class C, willhave access to all members present in both Class A and Class B. As a result of multi-levelinheritance 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 talkabout 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. 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 thebase class except constructors. In the code snippet below class B will inherit both M1 andM2 from Class A, but you cannot access M2 because of the private access modifier. Classmembers declared with a private access modifier can be accessed only with in the class. Wewill talk about access modifiers in our later article.Common Interview Question: Are private class members inherited to the derivedclass?Ans: Yes, the private members are also inherited in the derived class but we will not beable to access them. Trying to access a private base class member in the derived class willreport a compile time error.Using System;PublicclassA{Publicvoid M1 (){}Privatevoid M2 (){
  9. 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 classI have created a new write () method. So, now if I create an instance of child class and callthe write () method, the child class write () method will be called. The child class is hidingthe 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 childobject 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. 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. Polymorphismmeans many forms.Polymorphism is one of the fundamental concepts of OOP.Polymorphism provides following features:
  11. 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/OverridingCompile Time PolymorphismCompile time polymorphism is method and operators overloading. It is also called earlybinding.In method overloading method performs the different task at the different inputparameters.Runtime Time PolymorphismRuntime time polymorphism is done using inheritance and virtual functions. Methodoverriding 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:Dont 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. 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. 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 willwork according to the number of parameters and type of parameters.When and why to use method overloadingUse method overloading in situation where you want a class to be able to do something, butthere is more than one possibility for what information is supplied to the method that carriesout the task.You should consider overloading a method when you for some reason need a couple ofmethods that take different parameters, but conceptually do the same thing.Method overloading showing many forms.using System;namespacemethod_overloading_polymorphism{ ClassProgram
  14. 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. 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 overloadingIf 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 andthe number and type of parameters.There is no limit to how many overload of a method you can have. You simply declare themin 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 thesignature. We can override a function in base class by creating a similar function in derivedclass. This is done by using virtual/overridekeywords.Base class method has to be marked with virtual keyword and we can override it in derivedclass using override keyword.Derived class method will completely overrides base class method i.e. when we refer baseclass object created by casting derived class object a method in derived class will be called.
  16. 16. Example:// Base classpublicclassBaseClass{publicvirtualvoid Method1(){Console.Write("Base Class Method");}}// Derived classpublicclassDerivedClass : BaseClass{publicoverridevoid Method1(){Console.Write("Derived Class Method");}}// Using base and derived classpublicclassSample{publicvoidTestMethod(){// calling the overriden methodDerivedClassobjDC = newDerivedClass();objDC.Method1(); // calling the baesd class methodBaseClassobjBC = (BaseClass)objDC;objDC.Method1();}}Output---------------------Derived Class MethodDerived Class MethodConstructors and Destructors:Classes have complicated internal structures, including data and functions, objectinitialization and cleanup for classes is much more complicated than it is for simple datastructures. Constructors and destructors are special member functions of classes that areused to construct and destroy class objects. Construction may involve memory allocationand initialization for objects. Destruction may involve cleanup and deallocation of memoryfor objects.
  17. 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. Forexample, if you declare a constructor with protected access, only derived classes and friendscan use it to create class objects.The compiler automatically calls constructors when defining class objects and callsdestructors when class objects go out of scope. A constructor does not allocate memory forthe class object it’s this pointer refers to, but may allocate storage for more objects than itsclass object refers to. If memory allocation is required for objects, constructors canexplicitly call the new operator. During cleanup, a destructor may release objects allocatedby the corresponding constructor. To release objects, use the delete operator.Example of ConstructorclassC{ privateint x; privateint y; public C (int i, int j) { x = i; y = j; } publicvoid display () { Console.WriteLine(x + "i+" + y); }}Example of DestructorclassD
  18. 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:ClassDefines the abstract characteristics of a thing (object), including the things characteristics (its attributes,fields or properties) and the things 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), andthe ability to bark and sit (behaviors). Classes provide modularity and structure in an object-orientedcomputer program. A class should typically be recognizable to a non-programmer familiar with theproblem domain, meaning that the characteristics of the class should make sense in context. Also, thecode for a class should be relatively self-contained (generally using encapsulation). Collectively, theproperties and methods defined by a class are called members.ObjectA pattern (exemplar) of a class. The class of Dog defines all possible dogs by listing the characteristicsand behaviors they can have; the object Lassie is one particular dog, with particular versions of thecharacteristics. A Dog has fur; Lassie has brown-and-white fur.InstanceOne can have an instance of a class or a particular object. The instance is the actual object created atruntime. In programmer jargon, the Lassie object is an instance of the Dog class. The set of values of theattributes of a particular object is called its state. The object consists of state and the behaviour thats
  19. 19. defined in the objects class.MethodAn objects 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 Lassies methods. She may have other methods aswell, for example sit() or eat() or walk() or save_timmy(). Within the program, using a method usuallyaffects only one particular object; all Dogs can bark, but you need only one particular dog to do thebarking.Message passing"The process by which an object sends data to another object or asks the other object to invoke amethod."Also known to some programming languages as interfacing. For example, the object calledBreeder may tell the Lassie object to sit by passing a "sit" message which invokes Lassies "sit" method.The syntax varies between languages, for example: [Lassie sit] in Objective-C. In Java, code-levelmessage passing corresponds to "method calling". Some dynamic languages use double-dispatch ormulti-dispatch to find and pass messages.Inheritance"Subclasses" are more specialized versions of a class, which inherit attributes and behaviors from theirparent classes, and can introduce their own.For example, the class Dog might have sub-classes called Collie, Chihuahua, and GoldenRetriever. In thiscase, Lassie would be an instance of the Collie subclass. Suppose the Dog class defines a method calledbark() 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 defaultfurColor for a collie is brown-and-white. The Chihuahua subclass might specify that the bark() methodproduces a high pitch by default. Subclasses can also add new members. The Chihuahua subclass couldadd 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 objectwould also have the tremble() method, but Lassie would not, because she is a Collie, not a Chihuahua. Infact, inheritance is an "a... is a" relationship between classes, while instantiation is an "is a" relationshipbetween an object and a class: a Collie is a Dog ("a... is a"), but Lassie is a Collie ("is a"). Thus, the objectnamed Lassie has the methods from both classes Collie and Dog.Multiple inheritance is inheritance from more than one ancestor class, neither of these ancestors beingan ancestor of the other. For example, independent classes could define Dogs and Cats, and a Chimeraobject could be created from these two which inherits all the (multiple) behavior of cats and dogs. Thisis not always supported, as it can be hard both to implement and to use well.AbstractionAbstraction is simplifying complex reality by modelling classes appropriate to the problem, and workingat 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. 20. access Collie-specific attributes or behaviors, and as an Animal (perhaps the parent class of Dog) whencounting Timmys pets.Abstraction is also achieved through Composition. For example, a class Car would be made up of anEngine, Gearbox, Steering objects, and many more components. To build the Car class, one does notneed 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 objectscomposing the class interact with each other.EncapsulationEncapsulation 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 abark happens (e.g., by inhale() and then exhale(), at a particular pitch and volume). Timmy, Lassiesfriend, however, does not need to know exactly how she barks. Encapsulation is achieved by specifyingwhich classes may use the members of an object. The result is that each object exposes to any class acertain interface - those members accessible to that class. The reason for encapsulation is to preventclients of an interface from depending on those parts of the implementation that are likely to change infuture, thereby allowing those changes to be made more easily, that is, without changes to clients. Forexample, an interface can ensure that puppies can only be added to an object of the class Dog by codein that class. Members are often specified as public, protected or private, determining whether they areavailable to all classes, sub-classes or only the defining class. Some languages go further: Java uses thedefault access modifier to restrict access also to classes in the same package, C# and VB.NET reservesome members to classes in the same assembly using keywords internal (C#) or Friend (VB.NET), andEiffel and C++ allow one to specify which classes may access any member.PolymorphismPolymorphism allows the programmer to treat derived class members just like their parent classmembers. More precisely, Polymorphism in object-oriented programming is the ability of objectsbelonging to different data types to respond to method calls of methods of the same name, each oneaccording to an appropriate type-specific behavior. One method, or an operator such as +, -, or *, can beabstractly 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() fromAnimal, but their derived class methods override the methods of the parent class; this is OverridingPolymorphism. 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, forexample, may be used to perform integer addition, float addition, list concatenation, or stringconcatenation. Any two subclasses of Number, such as Integer and Double, are expected to addtogether 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 tolanguage, but most OOP languages support at least some level of overloading polymorphism. Many OOPlanguages also support Parametric Polymorphism, where code is written without mention of any specifictype and thus can be used transparently with any number of new types. Pointers are an example of asimple polymorphic routine that can be used with many different types of objects.
  21. 21. DecouplingDecoupling allows for the separation of object interactions from classes and inheritance into distinctlayers 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 witheach other. However, in practice decoupling often involves trade-offs with regard to which patterns ofchange to favor. The science of measuring these trade-offs in respect to actual change in an objectiveway is still in its infancy.