inheritance. types of inheritance implementation inheritance means that a type derives from a base...

34
Inheritance Inheritance

Upload: octavia-johnston

Post on 24-Dec-2015

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

InheritanceInheritance

Page 2: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

Types of InheritanceTypes of Inheritance

Implementation inheritance Implementation inheritance means that a means that a type derives from a base type, taking all the type derives from a base type, taking all the base type’s member fields and functions. base type’s member fields and functions.

With implementation inheritance, a derived With implementation inheritance, a derived type adopts the base type’s implementation of type adopts the base type’s implementation of each function, unless it is indicated in the each function, unless it is indicated in the definition of the derived type that a function definition of the derived type that a function implementation is to be overridden. implementation is to be overridden.

This type of inheritance is most useful when This type of inheritance is most useful when you need to add functionality to an existing you need to add functionality to an existing type, or where a number of related types share type, or where a number of related types share a significant amount of common functionality. a significant amount of common functionality.

Page 3: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

Interface inheritance Interface inheritance means that a type means that a type inherits only the signatures of the functions, inherits only the signatures of the functions, but does not inherit any implementations. but does not inherit any implementations.

This type of inheritance is most useful when This type of inheritance is most useful when you want to specify that a type makes you want to specify that a type makes certain features available. certain features available.

Interface inheritance is often regarded as Interface inheritance is often regarded as providing a contract: By deriving from an providing a contract: By deriving from an interface, a type is guaranteed to provide interface, a type is guaranteed to provide certain functionality to clients.certain functionality to clients.

Page 4: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

Multiple InheritanceMultiple Inheritance

Some languages such as C++ support what is Some languages such as C++ support what is known as known as multiple inheritancemultiple inheritance, which a class , which a class derives from more than one other class. derives from more than one other class.

C# does not support multiple implementation C# does not support multiple implementation inheritance.inheritance.

On the other hand, it does allow types to On the other hand, it does allow types to derive from multiple interfaces. derive from multiple interfaces.

This means that a C# class can derive from This means that a C# class can derive from one other class, and any number of interfaces. one other class, and any number of interfaces.

Page 5: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

Structs and ClassesStructs and Classes

structs don’t really support structs don’t really support implementation inheritance, but they do implementation inheritance, but they do support interface inheritance.support interface inheritance.

Structs Structs are always derived from are always derived from System.ValueType. System.ValueType.

They can also derive from any number of They can also derive from any number of interfaces.interfaces.

Classes Classes are always derived from one are always derived from one other class of your choosing. other class of your choosing.

They can also derive from any number of They can also derive from any number of interfaces.interfaces.

Page 6: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

Implementation InheritanceImplementation Inheritance

class MyDerivedClass : MyBaseClassclass MyDerivedClass : MyBaseClass

{{

// functions and data members here// functions and data members here

}} C# does not support private inheritance, C# does not support private inheritance, hence the absence of a public or private hence the absence of a public or private

qualifier on the base class namequalifier on the base class name

Page 7: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

If a class (or a struct) also derives from interfaces, If a class (or a struct) also derives from interfaces, then the list of base class and interfaces is then the list of base class and interfaces is separated by commas:separated by commas:

public class DerivedClass : BaseClass, Iface1, Iface2public class DerivedClass : BaseClass, Iface1, Iface2{{ // etc.// etc.}} For a struct, the syntax is as follows:For a struct, the syntax is as follows:public struct DerivedStruct : Iface1, Iface2public struct DerivedStruct : Iface1, Iface2{{

// etc.// etc.}}

Page 8: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

If you do not specify a base class in a class definition, the If you do not specify a base class in a class definition, the C# compiler will assume that System.Object is the base C# compiler will assume that System.Object is the base class. class.

class MyClass : Object // derives from System.Objectclass MyClass : Object // derives from System.Object{{

// etc.// etc.}} Is same as inIs same as inclass MyClass // derives from System.Objectclass MyClass // derives from System.Object{{

// etc.// etc.}} For the sake of simplicity, the second form is more For the sake of simplicity, the second form is more

common.common.

Page 9: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

Virtual MethodsVirtual Methods

By declaring a base class function as virtual, By declaring a base class function as virtual, we allow the function to be overridden in any we allow the function to be overridden in any derived classes:derived classes:

class MyBaseClassclass MyBaseClass{{ public virtual string VirtualMethod()public virtual string VirtualMethod() {{ return “This method defined in return “This method defined in

MyBaseClass”;MyBaseClass”; }}}}

Page 10: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

It is also permitted to declare a property as virtual. It is also permitted to declare a property as virtual. For a virtual or overridden property, the syntax is the For a virtual or overridden property, the syntax is the

same as for a non-virtual property with the exception same as for a non-virtual property with the exception of the keyword virtual, which is added to the definition. of the keyword virtual, which is added to the definition.

The syntax looks like this:The syntax looks like this:public virtual string ForeNamepublic virtual string ForeName{{

get { return foreName;}get { return foreName;}set { foreName = value;}set { foreName = value;}

}}private string foreName;private string foreName;

Page 11: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

In Java, by contrast, all functions are virtual.In Java, by contrast, all functions are virtual. it requires you to declare when a derived class’s it requires you to declare when a derived class’s

function overrides another function, using the function overrides another function, using the overrideoverride keyword: keyword:

class MyDerivedClass : MyBaseClassclass MyDerivedClass : MyBaseClass{{

public public overrideoverride string VirtualMethod() string VirtualMethod(){{return “This is an override defined in MyDerivedClass”;return “This is an override defined in MyDerivedClass”;}}

}}

Page 12: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

Neither member fields nor static Neither member fields nor static functions can be declared as virtual.functions can be declared as virtual.

Example: Example: virtual1.csvirtual1.cs

Page 13: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

Hiding MethodsHiding Methods

If a method with the same signature If a method with the same signature is declared in both base and derived is declared in both base and derived classes, but the methods are not classes, but the methods are not declared as virtual and override declared as virtual and override respectively, then the derived class respectively, then the derived class version is said to version is said to hidden by hidden by the base the base class version.class version.

Example: Example: virtual2.csvirtual2.cs

Page 14: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

Calling Base Versions of Calling Base Versions of FunctionsFunctions

Example: Example: virtual3.csvirtual3.cs

Page 15: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

Abstract Classes and Abstract Classes and FunctionsFunctions

An abstract class cannot be instantiated, while an abstract An abstract class cannot be instantiated, while an abstract function does not have an implementation, and function does not have an implementation, and

Must be overridden in any non-abstract derived class. Must be overridden in any non-abstract derived class. Obviously, an abstract function is automatically virtual Obviously, an abstract function is automatically virtual

(although you don’t need to supply the virtual keyword; (although you don’t need to supply the virtual keyword; doing so results in a syntax error). doing so results in a syntax error).

If any class contains any abstract functions, then that class If any class contains any abstract functions, then that class is also abstract and must be declared as such.is also abstract and must be declared as such.

abstract class Buildingabstract class Building{{public abstract decimal CalculateHeatingCost(); // abstract public abstract decimal CalculateHeatingCost(); // abstract

methodmethod}}

Page 16: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

abstract class Buildingabstract class Building

{{

private bool damaged = false; // fieldprivate bool damaged = false; // field

public abstract decimal public abstract decimal CalculateHeatingCost(); // abstract CalculateHeatingCost(); // abstract methodmethod

}}

Page 17: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

Sealed Classes and Sealed Classes and MethodsMethods

C# allows classes and methods to be declared as sealed. C# allows classes and methods to be declared as sealed. In the case of a class, this means that you can’t inherit from In the case of a class, this means that you can’t inherit from

that class. that class. In the case of a method, this means that you can’t override In the case of a method, this means that you can’t override

that method.that method.sealedsealed class FinalClass class FinalClass{{ … …....}}class DerivedClass : FinalClass // wrong. Will give compilation class DerivedClass : FinalClass // wrong. Will give compilation

errorerror{{ ……… ………..}}

Page 18: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

class MyClassclass MyClass{{

public public sealedsealed override void FinalMethod() override void FinalMethod(){{

// etc.// etc.}}

}}class DerivedClass : MyClassclass DerivedClass : MyClass{{

public override void FinalMethod() // compilation errorpublic override void FinalMethod() // compilation error{{}}

}}

Page 19: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

Constructors of Derived Constructors of Derived ClassesClasses

When you create an instance of a When you create an instance of a derived class, there is actually more derived class, there is actually more than one constructor at work. than one constructor at work.

The constructor of the class you The constructor of the class you instantiate isn’t by itself sufficient to instantiate isn’t by itself sufficient to initialize the class—the constructors initialize the class—the constructors of the base classes must also be of the base classes must also be called.called.

Page 20: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

public class Bpublic class B{{ private String name;private String name;

}}public class D : Bpublic class D : B{{ double x;double x;}}public class MainClasspublic class MainClass{{ static void Main()static void Main() {{ B b = new D();B b = new D(); }}}}

Page 21: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

constructors are called in order of constructors are called in order of System.Object first, then progressing down System.Object first, then progressing down the hierarchy until the compiler reaches the the hierarchy until the compiler reaches the class being instantiated. class being instantiated.

Notice also that in this process, each Notice also that in this process, each constructor handles initialization of the fields constructor handles initialization of the fields in its own class.in its own class.

That’s how it should normally work, and That’s how it should normally work, and when you start adding your own constructors when you start adding your own constructors you should try to stick to that principle.you should try to stick to that principle.

Page 22: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

Adding a No-Parameter Adding a No-Parameter Constructor in a HierarchyConstructor in a Hierarchy

public abstract class GCustomerpublic abstract class GCustomer{{

private string name;private string name;public GenericCustomer(): base() public GenericCustomer(): base() {{

name = “<no name>”;name = “<no name>”;}}

ORORpublic GenericCustomer()public GenericCustomer(){{

name = “<no name>”;name = “<no name>”;}}

Page 23: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

The The base and thisbase and this keywords are the keywords are the only keywords allowed in the line only keywords allowed in the line which calls another constructor.which calls another constructor.

Anything else causes a compilation Anything else causes a compilation error.error.

If base class no-parameter If base class no-parameter constructor is constructor is private private then you’ll get then you’ll get an error in derived class.an error in derived class.

Page 24: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

What’s happened is that the compiler has tried to generate What’s happened is that the compiler has tried to generate a default constructor for derived class, but not been able to a default constructor for derived class, but not been able to because the default constructor is supposed to invoke the because the default constructor is supposed to invoke the no-parameter base class constructor. no-parameter base class constructor.

By declaring that constructor as private, we’ve made it By declaring that constructor as private, we’ve made it inaccessible to the derived class. inaccessible to the derived class.

A similar error occurs if we supply a constructor to base A similar error occurs if we supply a constructor to base class, which takes parameters, but at the same time we fail class, which takes parameters, but at the same time we fail to supply a no-parameter constructor.to supply a no-parameter constructor.

In this case the compiler will not generate a default In this case the compiler will not generate a default constructor for base class, so when it tries to generate the constructor for base class, so when it tries to generate the default constructors for any derived class, it’ll again find default constructors for any derived class, it’ll again find that it can’t because a no parameter base class constructor that it can’t because a no parameter base class constructor is not available.is not available.

Page 25: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

ModifiersModifiers

Visibility ModifiersVisibility Modifiers

Page 26: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

Other ModifiersOther Modifiers

Page 27: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

InterfacesInterfaces

public interface IDisposablepublic interface IDisposable{{void Dispose();void Dispose();}} it is not permitted to supply implementations of it is not permitted to supply implementations of

any of the members of an interface. any of the members of an interface. In general, an interface can only contain In general, an interface can only contain

declarations of methods, properties, indexers, declarations of methods, properties, indexers, and events.and events.

You can never instantiate an interface; it only You can never instantiate an interface; it only contains the signatures of its members.contains the signatures of its members.

Page 28: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

An interface has neither constructors nor fields An interface has neither constructors nor fields (because that would imply some internal (because that would imply some internal implementation). implementation).

An interface definition is also not allowed to contain An interface definition is also not allowed to contain operator overloads, because interfaces are usually operator overloads, because interfaces are usually intended to be public contracts, and having intended to be public contracts, and having operator overloads would cause some operator overloads would cause some incompatibility problems with other .NET incompatibility problems with other .NET languages, such as Visual Basic.NET, which do not languages, such as Visual Basic.NET, which do not support operator overloading.support operator overloading.

It is also not permitted to declare modifiers on the It is also not permitted to declare modifiers on the members in an interface definition. members in an interface definition.

Interface members are always implicitly public, and Interface members are always implicitly public, and cannot be declared as virtual or static.cannot be declared as virtual or static.

Page 29: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

class SomeClass : IDisposableclass SomeClass : IDisposable{{

// this class MUST contain an implementation of the// this class MUST contain an implementation of the// IDisposable.Dispose() method, otherwise// IDisposable.Dispose() method, otherwise// you get a compilation error// you get a compilation errorpublic void Dispose()public void Dispose(){{

// implementation of Dispose() method// implementation of Dispose() method}}// rest of class// rest of class

}}

Page 30: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

Defining and Implementing Defining and Implementing InterfacesInterfaces

Example: Example: interface.csinterface.cs

Page 31: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

Interface references can in all respects be treated like class Interface references can in all respects be treated like class references—but the power of an interface reference is that references—but the power of an interface reference is that it can refer to any class that implements that interface. it can refer to any class that implements that interface.

For example, this allows us to form arrays of interfaces, For example, this allows us to form arrays of interfaces, where each element of the array is a different class:where each element of the array is a different class:IBankAccount[] accounts = new IBankAccount[2];IBankAccount[] accounts = new IBankAccount[2];accounts[0] = new SaverAccount();accounts[0] = new SaverAccount();accounts[1] = new GoldAccount(); // If implemented accounts[1] = new GoldAccount(); // If implemented IBankAccountIBankAccount

Note, however, that we’d get a compiler error if we tried Note, however, that we’d get a compiler error if we tried something like thissomething like thisaccounts[1] = new SomeOtherClass(); //Erroraccounts[1] = new SomeOtherClass(); //Error//As SomeOtherClass does NOT implement IBankAccount//As SomeOtherClass does NOT implement IBankAccount

Page 32: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

Derived InterfacesDerived Interfaces

public interface ITBAccount : public interface ITBAccount : IBankAccountIBankAccount

{{

bool TransferTo(IBankAccount bool TransferTo(IBankAccount destination, decimal amount);destination, decimal amount);

}}

Page 33: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

Because ITBAccount derives from Because ITBAccount derives from IBankAccount, it gets all the members of IBankAccount, it gets all the members of IBankAccount as well as its own. IBankAccount as well as its own.

That means that any class that implements That means that any class that implements ITBAccount must implement all the methods ITBAccount must implement all the methods of IBankAccount, as well as the new of IBankAccount, as well as the new TransferTo() method defined in ITBAccount. TransferTo() method defined in ITBAccount.

Failure to implement all of these methods Failure to implement all of these methods will result in a compilation error.will result in a compilation error.

Page 34: Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and

Example:Example: derInterface.csderInterface.cs