l Inheritance
- Inheritance allows a software developer to derive a new class from an existing one.
- The existing class is called the parent, super, or base class.
- The derived class is called a child or subclass.
- The child inherits characteristics of the parent.
- Methods and data defined for the parent class.
- The child has special rights to the parents methods and data.
- Public access like any one else
- Protected access available only to child classes (and their descendants).
- The child has its own unique behaviors and data.
- Base class & Derived class
class BaseClass
{
}
class DerivedClass : BaseClass
{
}
A child class inherits the methods and data defined for the parent class; however, whether a data or method member of a parent class is accessible in the child class depends on the visibility modifier of a member.
Private
Variables and methods declared with private visibility are not accessible in the child class
However, a private data member defined in the parent class is still part of the state of a derived class.
Public
Variables and methods declared with public visibility are accessible; but public variables violate our goal of encapsulation
Protected
There is a third visibility modifier that helps in inheritance situations: protected
Variables and methods declared with protected visibility in a parent class are only accessible by a child class or any class derived from that class
Some languages, e.g., C++, allow Multiple inheritance, which allows a class to be derived from two or more classes, inheriting the members of all parents.
C# and Java support single inheritance, meaning that a derived class can have only one parent class
Override
A child class can override the definition of an inherited method in favor of its own
That is, a child can redefine a method that it inherits from its parent
The new method must have the same signature as the parent's method, but can have a different implementation.
The type of the object executing the method determines which version of the method is invoked
Inheritance is transitive
An inherited member is continually passed down the line.Good class design puts all common features as high in the hierarchy as is reasonable. Avoids redundant code.
References and Inheritance
An object reference can refer to an object of its class, or to an object of any class derived from it by inheritance.
For example, if the Holiday class is used to derive a child class called Christmas, then a Holiday reference can be used to point to a Christmas object
Holiday day;
day=new Holiday();
day=new Christmas();
Dynamic Binding
A polymorphic reference is one which can refer to different types of objects at different times. It morphs!
The type of the actual instance, not the declared type, determines which method is invoked.
Polymorphic references are therefore resolved at run-time, not during compilation.
This is called dynamic binding.
Suppose the Holiday class has a method called Celebrate, and the Christmas class redefines it (overrides it).Now consider the following invocation:
day.Celebrate();
If day refers to a Holiday object, it invokes the Holiday version of Celebrate; if it refers to a Christmas object, it invokes the Christmas version
virtual, override and new
C# requires that all class definitions communicate clearly their intentions.
The keywords virtual, override and new provide this communication.
If a base class method is going to be overridden it should be declared virtual.
A derived class would then indicate that it indeed does override the method with the override keyword
If a derived class wishes to hide a method in the parent class, it will use the new keyword.
This should be avoided
Widening and Narrowing
Assigning an object to an ancestor reference is considered to be a widening conversion, and can be performed by simple assignment
Holiday day = new Christmas();
Assigning an ancestor object to a reference can also be done, but it is considered to be a narrowing conversion and must be done with a cast:
Christmas christ = new Christmas();
Holiday day = christ;
Christmas christ2 = (Christmas)day;
Question and Answer
1.How to prevent a class being inherited ?
Sealed
sealed class A
{
public int A,
public int B
} No class can be inherited from class A
2.When you are using shadowing if you want to access the base class method with derived class how can you access it?
public class Baseclass
{
public void Method1()
{
string a="Base Method" ;
}
}
public class Deriveclass:BaseClass
{
public new void Methaod1()
{
string a="Derive Methaod";
}
}
public class testApp
{
public static void main()
{
DeriveClass deriveObj=new DerideCalss();
BaseClass obj2=(BaseClass)deriveclass;
obj2.Method1()
}
}
3)What is the different between Class & object
Class:User defined datatype, method,property,abstarct charateistic
Object :instance of a class,which is created at rutime
4)Overloading and overrriding
overloading:more than one method with same name
overriding:Change behaviour of class in derive class using dynamic polymorphism
5)What is the difference between shadowing and overriding?
6) Common interface in C#
System.Data.IDataAdopter
System.Data.IDataParameter
System.Data.IDataReader
System.Data.IDataConnection
System.Data.IHttpModule
Common Sealed class in C#
System.Data.SqlClient.Sqlcommand
System.Data.SqlClient.Sqlconnetion
System.Data.SqlClient.SqlDataAdopter System.Data.SqlClient.SqlconnetionStringBuilder
Common abstract class in C#
System.Data.Common.DbCommand
System.Data.Common.DbConnection
System.Data.Common.DbDataReader
System.Data.Xml.Node
System.Data.Xml.Node
Common static classes
System.Math
System.Convert
System.Net
7.How many types of inheritances are there in C#?
Ans. There are two types of inheritance in C#.
a) Interface inheritance : When a class or interface is inheriting from another interface, is called interface inheritance.
b)Implementation inheritance : When a class is inheriting from another class, is called implementation inheritance.
8.What is Interface?
Ans. An interface is used to declare methods, properties, events etc. Interface dose not contain any definitions of these contructs. The class that inherit from interface has to define/implement all the members of that interface.
A class can inherit from more than one interfaces.
9.What is Abstract class?
Ans. An abstract class is a class that cant be instantiated. A class can be abstract if any one of the following occures:
a) Class is declared as Abstract
b) class is inherited from another abstract class but not implemented all abstract methods of the base class.
c) class that has some abstract methods
10)Static Classes and Static Class Members
A static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself
A child class inherits the methods and data defined for the parent class; however, whether a data or method member of a parent class is accessible in the child class depends on the visibility modifier of a member.
Private
Variables and methods declared with private visibility are not accessible in the child class
However, a private data member defined in the parent class is still part of the state of a derived class.
Public
Variables and methods declared with public visibility are accessible; but public variables violate our goal of encapsulation
Protected
There is a third visibility modifier that helps in inheritance situations: protected
Variables and methods declared with protected visibility in a parent class are only accessible by a child class or any class derived from that class
Some languages, e.g., C++, allow Multiple inheritance, which allows a class to be derived from two or more classes, inheriting the members of all parents.
C# and Java support single inheritance, meaning that a derived class can have only one parent class
Override
A child class can override the definition of an inherited method in favor of its own
That is, a child can redefine a method that it inherits from its parent
The new method must have the same signature as the parent's method, but can have a different implementation.
The type of the object executing the method determines which version of the method is invoked
Inheritance is transitive
An inherited member is continually passed down the line.Good class design puts all common features as high in the hierarchy as is reasonable. Avoids redundant code.
References and Inheritance
An object reference can refer to an object of its class, or to an object of any class derived from it by inheritance.
For example, if the Holiday class is used to derive a child class called Christmas, then a Holiday reference can be used to point to a Christmas object
Holiday day;
day=new Holiday();
day=new Christmas();
Dynamic Binding
A polymorphic reference is one which can refer to different types of objects at different times. It morphs!
The type of the actual instance, not the declared type, determines which method is invoked.
Polymorphic references are therefore resolved at run-time, not during compilation.
This is called dynamic binding.
Suppose the Holiday class has a method called Celebrate, and the Christmas class redefines it (overrides it).Now consider the following invocation:
day.Celebrate();
If day refers to a Holiday object, it invokes the Holiday version of Celebrate; if it refers to a Christmas object, it invokes the Christmas version
virtual, override and new
C# requires that all class definitions communicate clearly their intentions.
The keywords virtual, override and new provide this communication.
If a base class method is going to be overridden it should be declared virtual.
A derived class would then indicate that it indeed does override the method with the override keyword
If a derived class wishes to hide a method in the parent class, it will use the new keyword.
This should be avoided
Widening and Narrowing
Assigning an object to an ancestor reference is considered to be a widening conversion, and can be performed by simple assignment
Holiday day = new Christmas();
Assigning an ancestor object to a reference can also be done, but it is considered to be a narrowing conversion and must be done with a cast:
Christmas christ = new Christmas();
Holiday day = christ;
Christmas christ2 = (Christmas)day;
Question and Answer
1.How to prevent a class being inherited ?
Sealed
sealed class A
{
public int A,
public int B
} No class can be inherited from class A
2.When you are using shadowing if you want to access the base class method with derived class how can you access it?
public class Baseclass
{
public void Method1()
{
string a="Base Method" ;
}
}
public class Deriveclass:BaseClass
{
public new void Methaod1()
{
string a="Derive Methaod";
}
}
public class testApp
{
public static void main()
{
DeriveClass deriveObj=new DerideCalss();
BaseClass obj2=(BaseClass)deriveclass;
obj2.Method1()
}
}
3)What is the different between Class & object
Class:User defined datatype, method,property,abstarct charateistic
Object :instance of a class,which is created at rutime
4)Overloading and overrriding
overloading:more than one method with same name
overriding:Change behaviour of class in derive class using dynamic polymorphism
5)What is the difference between shadowing and overriding?
6) Common interface in C#
System.Data.IDataAdopter
System.Data.IDataParameter
System.Data.IDataReader
System.Data.IDataConnection
System.Data.IHttpModule
Common Sealed class in C#
System.Data.SqlClient.Sqlcommand
System.Data.SqlClient.Sqlconnetion
System.Data.SqlClient.SqlDataAdopter System.Data.SqlClient.SqlconnetionStringBuilder
Common abstract class in C#
System.Data.Common.DbCommand
System.Data.Common.DbConnection
System.Data.Common.DbDataReader
System.Data.Xml.Node
System.Data.Xml.Node
Common static classes
System.Math
System.Convert
System.Net
7.How many types of inheritances are there in C#?
Ans. There are two types of inheritance in C#.
a) Interface inheritance : When a class or interface is inheriting from another interface, is called interface inheritance.
b)Implementation inheritance : When a class is inheriting from another class, is called implementation inheritance.
8.What is Interface?
Ans. An interface is used to declare methods, properties, events etc. Interface dose not contain any definitions of these contructs. The class that inherit from interface has to define/implement all the members of that interface.
A class can inherit from more than one interfaces.
9.What is Abstract class?
Ans. An abstract class is a class that cant be instantiated. A class can be abstract if any one of the following occures:
a) Class is declared as Abstract
b) class is inherited from another abstract class but not implemented all abstract methods of the base class.
c) class that has some abstract methods
public abstract class SampleClassAbstract
{
public static void DisplayMessage()
{
Console.WriteLine("Static Method within Abstract Class Executed");
}
}
10)Static Classes and Static Class Members
A static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself
public static class TemperatureConverter { public static double CelsiusToFahrenheit(string temperatureCelsius) { // Convert argument to double for calculations. double celsius = Double.Parse(temperatureCelsius); // Convert Celsius to Fahrenheit. double fahrenheit = (celsius * 9 / 5) + 32; return fahrenheit; } public static double FahrenheitToCelsius(string temperatureFahrenheit) { // Convert argument to double for calculations. double fahrenheit = Double.Parse(temperatureFahrenheit); // Convert Fahrenheit to Celsius. double celsius = (fahrenheit - 32) * 5 / 9; return celsius; } }
public static class TemperatureConverter { public static double CelsiusToFahrenheit(string temperatureCelsius) { // Convert argument to double for calculations. double celsius = Double.Parse(temperatureCelsius); // Convert Celsius to Fahrenheit. double fahrenheit = (celsius * 9 / 5) + 32; return fahrenheit; } public static double FahrenheitToCelsius(string temperatureFahrenheit) { // Convert argument to double for calculations. double fahrenheit = Double.Parse(temperatureFahrenheit); // Convert Fahrenheit to Celsius. double celsius = (fahrenheit - 32) * 5 / 9; return celsius; } } class TestTemperatureConverter { static void Main() { Console.WriteLine("Please select the convertor direction"); Console.WriteLine("1. From Celsius to Fahrenheit."); Console.WriteLine("2. From Fahrenheit to Celsius."); Console.Write(":"); string selection = Console.ReadLine(); double F, C = 0; switch (selection) { case "1": Console.Write("Please enter the Celsius temperature: "); F = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine()); Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F); break; case "2": Console.Write("Please enter the Fahrenheit temperature: "); C = TemperatureConverter.FahrenheitToCelsius(Console.ReadLine()); Console.WriteLine("Temperature in Celsius: {0:F2}", C); break; default: Console.WriteLine("Please select a convertor."); break; } // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } /* Example Output: Please select the convertor direction 1. From Celsius to Fahrenheit. 2. From Fahrenheit to Celsius. :2 Please enter the Fahrenheit temperature: 20 Temperature in Celsius: -6.67 Press any key to exit. */The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name
public class Automobile { public static int NumberOfWheels = 4; public static int SizeOfGasTank { get { return 15; } } public static void Drive() { } public static event EventType RunOutOfGas; // Other non-static fields and properties... }
11)Can you declare a private class in a namespace ?
The classes in a namespace are internal, by default. However, you can
explicitly declare them as public only and not as private, protected, or protected
internal. The nested classes can be declared as private, protected, or
protected internal.