ganesh groups

25
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:

Post on 11-Sep-2014

662 views

Category:

Education


0 download

DESCRIPTION

java inheritence concept

TRANSCRIPT

Page 1: Ganesh groups

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

Page 2: Ganesh groups

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:

Page 3: Ganesh groups

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 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.

Page 4: Ganesh groups

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;

Public class BaseClass

{

    Public BaseClass ()

    {

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

    }

                                 

Page 5: Ganesh groups

    Public void Write ()

    {

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

    }

}

                                 

Public class ChildClass: BaseClass

{

                                 

    Public ChildClass ()

    {

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

    }

   

    Public static void Main ()

    {

        ChildClass CC = new ChildClass ();

        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:

Page 6: Ganesh groups

  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'.

public class A

{

}

public class B

{

}

public class C : A, B

{

}

Page 7: Ganesh groups

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;

Public class A

{

    Public void A_Method ()

    {

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

    }

}

Public class B: A

{

    Public void B_Method ()

    {

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

    }

}

Public class C: B

{

    Public void C_Method ()

    {

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

    }

                   

Page 8: Ganesh groups

    Public static void Main ()

    {

        C C1 = new C ();

        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;

Public class A

{

Public void M1 ()

{

}

Private void M2 ()

{

}

}

Page 9: Ganesh groups

Public class B: A

{

Public static void Main ()

{

B B1 = new B ();

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;

Public class Parent

{

    Public void Write ()

    {

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

    }

}

 

Page 10: Ganesh groups

Public class Child: Parent

{

    Public new void Write ()

    {

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

    }

   

    Public static void Main ()

    {

        Child C1 = new Child ();

        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. 

Page 11: Ganesh groups

Polymorphism is of two types: 

1. Compile time polymorphism/Overloading2. 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);

 

Page 12: Ganesh groups

Practical example of Method Overloading (Compile Time Polymorphism)

 

using System;

 

namespace method_overloading

{

    class Program

    {

        public class Print

        {

           

            public void display(string name)

            {

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

            }

 

            public void display(int age, float marks)

            {

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

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

            }

        }

       

        static void Main(string[] args)

        {

 

            Print obj = new Print ();

            obj.display ("George");

Page 13: Ganesh groups

            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;

 

namespace method_overloading_polymorphism

{

    Class Program

    {

        Public class Shape

        {

            Public void Area (float r)

Page 14: Ganesh groups

            {

                float a = (float)3.14 * r;

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

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

            }

 

            Public void Area(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);

 

            }

 

            public void 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);

            }

        }

 

        Static void Main (string[] args)

        {

            Shape ob = new Shape ();

            ob.Area(2.0f);

            ob.Area(20.0f,30.0f);

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

Page 15: Ganesh groups

            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 Overriding means 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/override keywords.

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 classpublic class BaseClass{public virtual void Method1(){Console.Write("Base Class Method");}}// Derived class

Page 16: Ganesh groups

public class DerivedClass : BaseClass{public override void Method1(){Console.Write("Derived Class Method");}}// Using base and derived classpublic class Sample{public void TestMethod(){// calling the overriden methodDerivedClass objDC = new DerivedClass(); objDC.Method1(); // calling the baesd class methodBaseClass objBC = (BaseClass)objDC; objDC.Method1();}}

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

Derived Class MethodConstructors 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

Page 17: Ganesh groups

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

class C{

       private int x;    

       private int y;

       public C (int i, int j)

       {

                 x = i;

                 y = j;

       }

       public void display ()     

       {

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

       }

}

Example of Destructor

class D {

        public D ()

        {

            // constructor

        }         

        ~D ()

        {

           // Destructor

Page 18: Ganesh groups

        }

}an oop 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 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.

ObjectA 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.

InstanceOne 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.

MethodAn 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.

Page 19: Ganesh groups

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.

AbstractionAbstraction 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.

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 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

Page 20: Ganesh groups

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.

PolymorphismPolymorphism 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.

DecouplingDecoupling 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.