I am so confused about the abstract classes I know it is not a question related to programing problem.But this is the only place I can find solution for this.
As everybody know that abstract classes cannot be instantiated and you cannot implement anything in these classes. We can just derive these classes and can do implementation in derived classes. So my question is this:
If we have to implement logic in derived classes and we have to use complete function and classes in derived class then why we create abstract classes?
Can anybody give me a clear explanation for this? If there is any good example then please tell me
When you use an abstract class you have some implementation in the abstract class, but leave bits that are specific to a derived class as abstract. For example, I might define an abstract class for all shapes:
abstract class Shape
{
public int Sides{get;protected set;}
public abstract int CalculateArea();
}
All shapes have a particular number of sides, so that can go into the general case (ie Shape). The calculcation of the area depends on the type of shape (triangle, square etc) so if belongs in the derived class. However, I'd like users of my class hierarchy to be able to call CalculateShape from any Shape instance.
How I create a derived class and override CalculateLength:
class Square : Shape
{
public Square(int sideLength)
{
this.Sides = 4;
this.SideLength = sideLength;
}
public int SideLength{get;private set;}
public override int CalculateArea()
{
return this.SideLength * this.SideLength
}
}
Note that I haven't reimplemented all of Shape in Square, I have only implemented the Square specific bits.
According to MSDN,
An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class.
The above are all the technical explanation, in layman style it's like creating a blueprint that provide info what all things it can do, and all the derived classes will provide there own process how to do that.
For example, we can think of Driver and we know there are many driver types like auto-rickshaw driver, truck driver, tractor driver etc. but all have a common denominator functionality that is Driving but each of Driving process will be different, thus
Driver: abstract class with Driving function
Auto-RickshawDriver: Derived class extending Driver class
Your question,
If we have to implement logic in derived classes and we have to use complete function and classes in derived class then why we create abstract classes?
Just because we want to define some common functionality, that every other class has to abide to be member of it. In general term creating groups based on functionality, i.e. we can say if that class belong to a group we are damn sure that those common functionality of that group will be present.
Abstract classes will contain common incomplete implementation which can then be reused from multiple derived classes.
protected methods inside it can only be called from inside the derived classes.
abstract methods need to be implemented in derived classes.
virtual methods can be ocerriden in derived classes
In .NET framework you can find many examples of such abstract classes, e.g. System.IO.Stream.
The code using all those classes can refer to them using their common public interface of Stream, not having to know which concrete Stream implementation it uses.
Just to correct a minor detail, abstract classes can be partially abstract or fully abstract, depending on whether they are partially implemented (in which case we commonly call them abstract classes) or not implemented at all and have no member variable (in which case we commonly call them interfaces).
They are many uses for abstract classes, most of them implying the ability to extend behaviour of code without modifying this code.
Let's suppose that you want to write a program that reads data from the keyboard and writes it to the screen. (I'll use C# for the code, because it's slightly shorter than C++)
void Copy() {
int c;
while((c = Console.Read()) != -1) {
Console.Write(c);
}
}
Now, the requirements change. You want to be able to read from a file instead of the keyboard, depending on a variable.
TextReader reader;
void Copy(bool readFromFile) {
int c;
while((c = ReadNextChar(readFromFile)) != -1) {
Console.Write(c);
}
}
int ReadNextChar(bool readFromFile) {
if(readFromFile) {
return reader.Read();
} else {
return Console.Read();
}
}
Now, you want to be able to read from the network. The bool becomes an enum, the if/else becomes a switch/case etc. etc.
enum ReadMode { FROM_CONSOLE, FROM_FILE, FROM_NETWORK };
TextReader fileReader;
TextReader networkReader;
void Copy(ReadMode readMode) {
int c;
while((c = ReadNextChar(readMode)) != -1) {
Console.Write(c);
}
}
int ReadNextChar(ReadMode readMode) {
switch(readMode) {
case FROM_CONSOLE:
return Console.Read();
case FROM_FILE:
return reader.Read();
case FROM_NETWORK:
return networkReader.Read();
default:
return -1;
}
}
And this can go on. And the same requests may occur for the writing. The problem with this program is that it explicitly lists all the ways you can read from a file. To read from another source, you have to modify the code (add a member to the enum ReadMode and add a case in ReadNextChar. You may deem this OK if you have access to the source code, but if it's an external library, you may deem crappy this way of doing because you can not extend this wonderful copy library.
Now meet abstract classes. What if you abstracted all the sources into a single Source concept, because after all, all you need is to ask the source for an int. So let's write this abstract concept.
interface Source {
int ReadNextChar();
}
And all three implementations:
class KeyboardSource : Source {
int ReadNextChar() {
return Console.Read();
}
}
class FileSource : Source {
TextReader reader;
FileSource(string path) {
reader = new StreamReader(path);
}
int ReadNextChar() {
return reader.Read();
}
}
class NetworkSource : Source {
TextReader reader;
NetworkSource (string url) {
reader = new StreamReader(path);
}
int ReadNextChar() {
return reader.Read();
}
}
And implement the copy function:
void Copy(Source source) {
int c;
while((c = source.ReadNextChar()) != -1) {
Console.Write(c);
}
}
Now any source type you want to add, you just have to implement a new derivative of Source, without modifying existing code. The Copy program remains correct and untouched, so do the existing derivatives of Source.
This is called polymorphism. If you look at the dependencies of the Copy, they don't include code concerning either files, network, or user interface. It can be packaged in a library, allowing users to extend the types of sources from which it can read.
Hope it's clear. The same can be done for the writing part.
Regard this example:
abstract class A
{
// forces subclasses to implement
abstract void method1();
virtual void method2()
{
// some common logic
// that sublcasses can
// modify
}
protected void method3()
{
// some common logic
}
}
class B : A
{
void method1()
{
// needs to be implemented
}
override void method2()
{
// optional: e.g. something added
base.method1();
}
}
class C : A {
//...
}
No you can specify common logic in the base class, as well as define abstract methods that every subclass will have. So your baseclass works like an interface. You can call method1() to every instance of B and C.
So: No! It's absolutely no waste of time ;-).
It's not,
Assume you have a base class
class Foo{
public String getGreetingMessage(){
return "Hello " + getName();
}
public abstract String getName();
}
and you have a derived class
class Bar extends Foo{
public String getName(){
return "MeMamo";
}
}
class Boo extends Foo{
public String getName(){
return "Boo";
}
}
And in another class, I call the method from derived,
Bar b = new Bar();
System.out.println(b.getGreetingMessage()); // Hello MeMamo.
Boo boo = new Boo();
System.out.println(boo.getGreetingMessage()); // Hello Boo;
I don't need to write the base method all over again.
Assume that operation for another derived class.
Related
Hi I'm creating a geometry library in C#...
I have an abstract class shape.
I have defined a class vector (also representing (x,y) points).
I would like to use a variety of geometrical objects, curves, lines, arcs, paths etc
To do this I've defined an abstract Segment class and derived a number of classes e.g. LineSegment (see below), CurveSegment, ArcCircleSegment, BezierCurveSegment, HalfInfiniteLine etc.
I've also defined a class Path (NOT abstract) which is intended to represent a number of segments joined together (like what you might get from a drawing application). In this i include a List member of Segments (List<Segment>).
Then i wish to derive classes from Path, the key example being LinePath which should contain only LineSegments. The problem i have is i'd like to be able to call the get property on a LinePath object assuming it'll return a LineSegment. Is this possible without explicitly casting each time?
I want to avoid making Path abstract as i might have a path of multiple Segment types.
public class LineSegment : Segment
{
private vector m_start;
private vector m_end;
private vector m_vector;
public vector Start
{
get { return m_start; }
set { m_start = value; }
}
public vector End
{
get { return m_end; }
set { m_end = value; }
}
public vector Vec
{
get { return m_vector; }
set { m_vector = value; }
}
public double Length()
{
return Vec.length();
}
public LineSegment(vector v0, vector v1):base()
{
this.Start.x = v0.x;
this.Start.y = v0.y;
this.End.x = v1.x;
this.End.y = v1.y;
this.Vec = this.End - this.Start;
}
}
If I understand what you want correctly, you can do something like this:
Make your path class generic
public class Path<T> where T : Segment
{
private IList<T> segments = new List<T>();
public IList<T> Segments { get { return this.segments; } }
}
You can then create your LinePath object
public class LinePath : Path<LineSegment>
{
}
that way you can ensure that all segments in your LinePath.Segments are LineSegments while still being able to re-use the Path class for any operations which act against a Segment.
You can redefine the Path property on your derived classes. LinePath can have:
public new List<LineSegment> Segments
{
get
{
return (List<LineSegment>)base.Segments;
}
}
This way you will enforce the correct type usage.
When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.
For e.g. again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods / properties as abstract so they could be overridden by child classes.
–> The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
For example a class library may define an abstract class that is used as a parameter to many of its functions and require programmers using that library to provide their own implementation of the class by creating a derived class.
Use an abstract class
When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. ( COM was designed around interfaces.)
Use an abstract class to define a common base class for a family of types.
Use an abstract class to provide default behavior.
Subclass only a base class in a hierarchy to which the class logically belongs.
We define interface as below:
interface IMyInterface
{
void MethodToImplement();
}
And impliments as below:
class InterfaceImplementer : IMyInterface
{
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
instead of creating a interface , why can we use the function directly like below :-)
class InterfaceImplementer
{
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
Any thoughts?
You are not implementing the interface in the bottom example, you are simply creating an object of InterfaceImplementer
EDIT: In this example an interface is not needed. However, they are extremely useful when trying to write loosely coupled code where you don't have to depend on concrete objects. They are also used to define contracts where anything implementing them has to also implement each method that it defines.
There is lots of information out there, here is just a brief intro http://www.csharp-station.com/Tutorials/Lesson13.aspx
If you really want to understand more about interfaces and how they can help to write good code, I would recommend the Head First Design Patterns book. Amazon Link
instead of creating a interface , why
can we use the function directly like
below
Are you asking what the point of the interface is?
Creating an interface allows you to decouple your program from a specific class, and instead code against an abstraction.
When your class is coded against an interface, classes that use your class can inject whichever class they want that implements this interface. This facilitates unit testing since not-easily-testable modules can be substituted with mocks and stubs.
The purpose of the interface is for some other class to be able to use the type without knowing the specific implementation, so long as that type conforms to a set of methods and properties defined in the interface contract.
public class SomeOtherClass
{
public void DoSomething(IMyInterface something)
{
something.MethodToImplement();
}
}
public class Program
{
public static void Main(string[] args)
{
if(args != null)
new SomeOtherClass().DoSomething(new ImplementationOne());
else
new SomeOtherClass().DoSomething(new ImplementationTwo());
}
}
Your example doesn't really follow that pattern, however; if one that one class implements the interface, then there really isn't much of a point. You can call it either way; it just depends on what kind of object hierarchy you have and what you intend to do for us to say whether using an interface is a good choice or not.
To sum: Both snippets you provide are valid code options. We'd need context to determine which is a 'better' solution.
Interfaces are not required, there is nothing wrong with the last section of code you posted. It is simply a class and you call one of it's public methods. It has no knowledge that an interface exists that this class happens to satisfy.
However, there are advantages:
Multiple Inheritance - A class can only extend one parent class, but can implement any number of interfaces.
Freedom of class use - If your code is written so that it only cares that it has an instance of SomethingI, you are not tied to a specific Something class. If tomorrow you decide that your method should return a class that works differently, it can return SomethingA and any calling code will not need to be changed.
The purpose of interfaces isn't found in instantiating objects, but in referencing them. Consider if your example is changed to this:
static void Main()
{
IMyInterface iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}
Now the iTmp object is of the type IMyInterface. Its specific implementation is InterfaceImplementer, but there may be times where the implementation is unimportant (or unwanted). Consider something like this:
interface IVehicle
{
void MoveForward();
}
class Car : IVehicle
{
public void MoveForward()
{
ApplyGasPedal();
}
private void ApplyGasPedal()
{
// some stuff
}
}
class Bike : IVehicle
{
public void MoveForward()
{
CrankPedals();
}
private void CrankPedals()
{
// some stuff
}
}
Now say you have a method like this somewhere:
void DoSomething(IVehicle)
{
IVehicle.MoveForward();
}
The purpose of the interface becomes more clear here. You can pass any implementation of IVehicle to that method. The implementation doesn't matter, only that it can be referenced by the interface. Otherwise, you'd need a DoSomething() method for each possible implementation, which can get messy fast.
Interfaces make it possible for an object to work with a variety of objects that have no common base type but have certain common abilities. If a number of classes implement IDoSomething, a method can accept a parameter of type IDoSomething, and an object of any of those classes can be passed to it. The method can then use all of the methods and properties applicable to an IDoSomething without having to worry about the actual underlying type of the object.
The point of the interface is to define a contract that your implementing class abides by.
This allows you to program to a specification rather than an implementation.
Imagine we have the following:
public class Dog
{
public string Speak()
{
return "woof!";
}
}
And want to see what he says:
public string MakeSomeNoise(Dog dog)
{
return dog.Speak();
}
We really don't benefit from the Interface, however if we also wanted to be able to see what kind of noise a Cat makes, we would need another MakeSomeNoise() overload that could accept a Cat, however with an interface we can have the following:
public interface IAnimal
{
public string Speak();
}
public class Dog : IAnimal
{
public string Speak()
{
return "woof!";
}
}
public class Cat : IAnimal
{
public string Speak()
{
return "meow!";
}
}
And run them both through:
public string MakeSomeNoise(IAnimal animal)
{
return animal.Speak();
}
Sounds like silly idea but I was wondering if it's possible somehow.
Is it possible to change the base class of a derived class at runtime? Of course, there are lot of ifs and buts and the the question of why would someone do it and its a bad design probably and all that.
Keeping all those aside (even though they might be perfectly valid), let's say, just for kicks or to show your nerdiness, is it possible in C# or any language for that matter?
So something like:
public class baseOriginal {
public string justAProperty;
}
public class baseSwapped {
public int sillyNumber;
}
public class derivedClass : baseOriginal {
public bool iAmDumb;
}
void Main() {
baseOriginal derived = new derivedClass ();
Console.WriteLine(derived.justAProperty);
baseSwapped derivedSwapped = (??);
Console.WriteLine(derivedSwapped.sillyNumber);
}
It isn't possible in C#. Probably what you want is more of a prototype-based solution commonly found in dynamic languages like JavaScript where you can "extend" the functionality of the object by adding to how it's defined.
But to accomplish what your code hints at doing, you can have the swappable classes inherit from a common ancestor class. That way you can assign instances of each to their decendents.
public class baseClassAncestor{
}
public class baseOriginal:baseClassAncestor {
public string justAProperty;
}
public class baseSwapped:baseClassAncestor {
public int sillyNumber;
}
public class derivedClass : baseOriginal {
public bool iAmDumb;
}
You can do one time base class swap by loading different assemblies that implement base class BEFORE using derived class. But this approach will not make your exact code working as you will not be able to compile that - but moving access to methods of different base classes to separate functions could be made working.
You add UnionBase class that contains all possible methods/properties from all base classes so you can compile your Main code against the assembly with this class. Than at run time you load assembly that has contains your particular base class.
Usual warning: You need to have very good reasons and understanding for going this route. I.e. existing external code is a reason to consider such approach.
"Don't do it at home, performed on a closed course by trained professional".
One more possible workaround could be implemented using some AOP solution that is based on compile-time weaving, i.e. PostSharp, which is able to seamlessly inject new methods and interfaces to existing types as well as modify (intercept) existing ones.
There is actually a good reason where you may want to swap the base class. Let say you want to modify the base class but you don't wan't to perturb the current code base as it is shared among other teams. Let say there are 10+ derived class that inherits from base. You could create 10+ custom derived classes to override the base class but that is a lot of work. Here is what you do. The key to the problem is to create an interface and a base proxy class.
class Program
{
static void Main(string[] args)
{
IActionable action = new Derived<Base1>();
action.open();
action = new Derived<Base2>();
action.open();
}
}
// Proxybase is a fake base class. ProxyBase will point to a real base1 or
// base2
public class Derived<T>:ProxyBase,IActionable
{
public Derived():base(typeof(T))
// the open function is not overriden in this case allowing
// the base implementation to be used
}
// this looks like the real base class but it is a fake
// The proxy simply points to the implementation of base1 or base2 instead
public abstract class ProxyBase: IActionable
{
IActionable obj;
public ProxyBase(Type type,params object[] args)
{
obj = (IActionable)Activator.CreateInstance(type,args);
}
public virtual void open()
{
obj.open();
}
}
// notice base1 and base2 are NOT abstract in this case
// consider this the original implementation of the base class
public class Base1: IActionable
{
public virtual void open()
{
Console.WriteLine("base1 open");
}
}
// here base2 acquired the functionality of base1 and hides base1's open
function
// consider this implementation the new one to replace the original one
public class Base2: Base1, IActionable
{
public new virtual void open()
{
Console.WriteLine("base2 open");
}
}
public interface IActionable
{
void open();
}
The result would be as follows
base1 open
base2 open
UPDATE:
Although this answer works, the reality is that inheritance introduces coupling which makes this exercise difficult at best. Also, in a practical scenario, your requirements may lead you to want to derive from multiple base class which is not possible in c#. If you want to interchange the base class you are best to use the bridge design pattern (which in fact avoids inheritance altogether thus avoiding the coupling).
The closest thing I can think of is the following:
http://msdn.microsoft.com/en-us/library/dd264736.aspx
static void Main(string[] args)
{
ExampleClass ec = new ExampleClass();
// The following line causes a compiler error if exampleMethod1 has only
// one parameter.
//ec.exampleMethod1(10, 4);
dynamic dynamic_ec = new ExampleClass();
// The following line is not identified as an error by the
// compiler, but it causes a run-time exception.
dynamic_ec.exampleMethod1(10, 4);
// The following calls also do not cause compiler errors, whether
// appropriate methods exist or not.
dynamic_ec.someMethod("some argument", 7, null);
dynamic_ec.nonexistentMethod();
}
class ExampleClass
{
public ExampleClass() { }
public ExampleClass(int v) { }
public void exampleMethod1(int i) { }
public void exampleMethod2(string str) { }
}
I have no idea if the dynamic language runtime can do what you want it to do.
Closest you could get would be to
derive from both types by defining at
least one as an interface, then
casting derived from one to the other.
I would have to agree, based on the example this suggestion would satisfy what he wants to do, it also is a better design then what he actually wants to do.
Closest you could get would be to derive from both types by defining at least one as an interface, then casting derived from one to the other.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I cannot get my head around how to use interfaces and why they are needed. Can someone please show me a simple example?
interface IFlyable
{
void Fly();
}
class Bird : IFlyable
{
public void Fly() { }
}
class Plane : IFlyable
{
public void Fly() { }
}
List<IFlyable> things = GetBirdInstancesAndPlaneInstancesMixed();
foreach(IFlyable item in things)
{
item.Fly();
}
Bird and Plane have no common base class except Object, but you can see using the same interface we can deal with them grouply in our program, because they have the same "feature": Fly.
public interface ISpeaks
{
string Speak();
}
public class Dog : Mammal, ISpeaks
{
public string Speak() { return "Woof!"; }
}
public class Person : Mammal, ISpeaks
{
public string Speak() { return "Hi!"; }
}
//Notice Telephone has a different abstract class
public class Telephone : Appliance, ISpeaks
{
public Person P { get; set; }
public Telephone(Person p)
{
P = p;
}
public string Speak() { return P.Speak(); }
}
[Test]
public void Test_Objects_Can_Speak()
{
List<ISpeaks> thingsThatCanSpeak = new List<ISpeaks>();
//We can add anything that implements the interface to the list
thingsThatCanSpeak.Add(new Dog());
thingsThatCanSpeak.Add(new Person());
thingsThatCanSpeak.Add(new Telephone(new Person()));
foreach(var thing in thingsThatCanSpeak)
{
//We know at compile time that everything in the collection can speak
Console.WriteLine(thing.Speak());
}
}
This is useful because we can code against the interface rather than implementation and because we can use multiple interfaces on a single class, we are more flexible than if we used an Abstract class.
Interfaces are somehow class definition alike, a sort of contract between the interface and the class implementing it.
An interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition.
A .NET class cannot use multi-inheritance. As such, we rely on interfaces, and a class can implement as much interfaces as you wish. On the contrary, a class inheritance has to be single. For instance:
public class Customer : Person, Company {
}
This code is not allowed in any .NET languages that I know (C#/VB.NET).
To counter this lack, if we may say so, we rely on interfaces.
public interface IPerson {
string Name
string Address
string StateProvince
string ZipPostalCode
string Country
long PhoneNumber
}
public interface ICompany {
string CreditTerm
string BillingAddress
string ShippingAddress
string ContactName
long ContactPhoneNumber
long FaxNumber
}
public class Customer : IPerson, ICompany {
// Properties implementations here.
}
In this way, interfaces are like a workaround somehow to multi-inheritance.
On the other hand, interfaces can be used as a contract for methods. Let's say you got a method that take an ICompany as an input parameter. You are now sure to have the properties defined in the ICompany interface to perform your work within the method.
public BillCompany(ICompany company) {
// Bill company here...
}
Then, your Customer class correspond to what you are expecting, since it implements the ICompany interface.
Let's make another class, whose definition would only implement the IPerson interface.
public class Individual : IPerson {
// Interface implementation here...
}
Then, your BillCompany() method could not accept an instance of the Individual class, as it doesn't show requirements (properties, etc.) for a company.
In short, interfaces are a good way to bind by contract your methods to what will be accepted, like inheritance.
There are indeed some precautions to take while working with Interfaces, a change to an interface will break your code, as an enforcing rule to implement the new member within all implementing classes, which class inheritance does not.
Does this help?
I like this blog post that I read the other day: http://simpleprogrammer.com/2010/11/02/back-to-basics-what-is-an-interface/
Many people, myself included, have created interfaces that have a 1 to 1 mapping to the class they are representing but this is not always a good thing and that article explains why.
An interface is useful when you have a given contract you want an object to fulfill but you don't really care about how they fulfill it. That's an implementation detail left to the class itself.
So let's say you have a method that's job is to process save requests. It does not perform the actual act of saving, it just processes the requests. As a result, it can take a List<ICanSave>, where ICanSave is an interface. The objects in that list can be any type that implements that interface. It can be a mix, or it can contain just one type. You're just concerned that it implements the interface.
public interface ICanSave
{
void Save();
}
In your method, you might have something simple like
public void SaveItems(List<ICanSave> items)
{
foreach (var item in items)
{
item.Save();
}
}
How are those items being saved? You don't care! That, again, is an implementation detail for the class implementing the interface. You just want whatever class that enters the method to have that ability.
You could have a class that implements the interface that persists data to the file system. Another might save to a database. Another may call some external service. Etc. That's left for the author of the class to decide. You might even have a stubbed class for a unit test that does nothing at all.
That's just one use-case scenario, there are many others, several in the BCL. IEnumerable<T> is a good one, it is implemented by things such as ICollection<T> and IList<T>, which are in turn implemented by concrete types such as Array and List<T>. It's the interface which makes many of the programming constructs you may be accustomed to useful, such as LINQ. LINQ doesn't care about the actual implementation* of the class, it just wants to be able to enumerate it and perform the proper filtering and/or projection.
IDisposable is another good BCL example. You want to know that a class needs to clean up after itself. What specifically it needs to clean up is left up to the class, but by nature of it implementing IDisposable, you know it needs to clean up after itself, so you preferrably wrap its use in a using statement or you manually ensure that you call .Dispose once you've finished working with the object.
*LINQ actually does optimize for some interfaces.
Simple example of interface Animal with two implementation of class animal (you have an unique description for animal and many implementation in class dog, cat...)
public interface IAnimal
{
string GetDescription();
}
class Cat : IAnimal
{
public string GetDescription()
{
return "I'm a cat";
}
}
class Program
{
static void Main(string[] args)
{
Cat myCat = new Cat();
Console.WriteLine(myCat.GetDescription());
}
}
"I've got a bunch of classes here that I want to treat the same way, for a certain amount of functionality."
So, you write a contract.
Real-world example: I'm writing a wizard. It has a bunch of pages, some of which (but not all) are UserControls. They all need a common set of operations, so the controlling class can treat them all the same. So I have an IPage interface that they all implement, with operations like initializing the page, saving the user's choices, et cetera. In my controller, I simply have a List, and don't have to know what page does what; I simply call the interface's Save()s and Initialize()s.
Here is the main points of Interface,
1.We can call same method using different classes with different out put of same methods.
Simple Example:
class Mango : abc
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
Mango refDemo = new Mango();
refDemo.mymethod();
Orange refSample = new Orange();
refSample.mymethod();
}
public void mymethod()
{
System.Console.WriteLine("In Mango : mymethod");
}
}
interface abc
{
void mymethod();
}
class Orange : abc
{
public void mymethod()
{
System.Console.WriteLine("In Orange : mymethod");
}
}
2.can call same method using same interface with different classes.
class Mango : abc
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
abc refabc = new Mango();
refabc.mymethod();
abc refabd = new Orange();
refabd.mymethod();
Console.ReadLine();
}
public void mymethod()
{
System.Console.WriteLine("In Mango : mymethod");
}
}
interface abc
{
void mymethod();
}
class Orange : abc
{
public void mymethod()
{
System.Console.WriteLine("In Orange : mymethod");
}
}
Well from MSDN, "An interface defines a contract. A class or struct that implements an interface must adhere to its contract."
On this page, there are several examples of what an interface looks like, how a class inherits from an interface and a full blown example of how to implement an interface.
Hope this helps out some.
Question Heading seems to be little confusing, But I will Try to clear my question here.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public abstract class Employee
{
private string name;
private int empid;
BenefitPackage _BenefitPackage = new BenefitPackage();
public string Name
{
get { return this.name; }
set { this.name = value; }
}
public int EmpId
{
get { return this.empid; }
set
{
if (value == 1)
return;
this.empid = value; }
}
public Employee(string Name, int EmpId)
{
this.Name = Name;
this.EmpId = EmpId;
}
public Employee()
{ }
public abstract void GiveBonus();
}
public class Manager : Employee
{
private int noofstockoptions;
public override void GiveBonus()
{
Console.WriteLine("Manger GiveBonus Override");
}
public int NoOfStockOptions
{
get { return this.noofstockoptions; }
set { this.noofstockoptions = value; }
}
public Manager(string Name,int EmpId, int NoOfStockOptions):base(Name,EmpId)
{
this.NoOfStockOptions=NoOfStockOptions;
}
}
public class SalesPerson:Employee
{
private int noofsales;
public int NoOfSales
{
get { return this.noofsales; }
set { this.noofsales = value; }
}
public SalesPerson(string Name, int EmpId, int NoOfSales):base(Name,EmpId)
{
this.NoOfSales = NoOfSales;
}
public override void GiveBonus()
{
Console.WriteLine("Hi from salesperson");
}
}
public sealed class PTSalesPerson : SalesPerson
{
private int noofhrworked;
public int NoOfHrWorked
{
get { return this.noofhrworked; }
set { this.noofhrworked = value; }
}
public PTSalesPerson(string Name, int EmpId, int NoOfSales,int NoOfHrWorked):base(Name,EmpId,NoOfSales)
{
this.NoOfHrWorked = NoOfHrWorked;
}
//public new void GiveBonus()
//{
// Console.WriteLine("hi from ptsalesperson");
//}
}
class BenefitPackage
{
public int Bonus;
public int GiveBonus()
{
int i = 200;
return i;
}
private class innerPublic
{
public int innerBonus;
}
}
class MainClass
{
public static void Main()
{
Manager _Manager=new Manager("Vaibhav",1,50);
PTSalesPerson _PTSalesPerson = new PTSalesPerson("Shantanu", 1, 4, 6);
_Manager.GiveBonus();
Employee _emp;
//_emp = new Employee("new emp",4);
//_emp.GiveBonus();
_PTSalesPerson.GiveBonus();
((SalesPerson)_PTSalesPerson).GiveBonus();
Console.ReadLine();
}
}
}
Please do not try to understand the whole code. I am summarising it.
Employee is a Abstract class, which have an abstract method GiveBonus
SalesPerson is a deriving from Employee. SalesPerson has to give definition to abstract Method GiveBonus.(SalesPerson can not be Abstract)
PTSalesPerson is deriving from SalesPerson.
Now my question is, How can I force PTSalesPerson to have its own implementation of GiveBonus.
I think you're thinking about this the wrong way. The language designers did not say to themselves "what we really need is a way to mark a method as must be overridden, let's invent this thing called abstract". They said "A virtual method lets us represent the idea that every derived type of this base type should be able to do this method. But what if there is no sensible code that can possibly go in the base class version of the method? I know, let's invent this thing called an abstract method for that circumstance."
That's the problem that abstract methods were intended to solve: you have a method common to all derived classes but no sensible base class implementation, NOT "I need a way to force my derived types to provide an implementation". That derived types are forced to provide an implementation is a consequence of the solution, but not the problem intended to be solved in the first place.
The C# language does not have a mechanism for the problem "I must force my subtype to provide their own implementation of this method" because that's not a problem that the language designers, to my knowledge, ever considered would be a problem for the majority of our customers.
So my question to you is: why do you want to do this? Surely it is up to the developer of the derived class to determine whether or not the base class implementation is correct for the derived class or not. That's not up to you. And even if you did have some way to do that, what would stop the developer from simply saying
override void M() { base.M(); }
?
Can you explain what purpose you have for attempting to force this work upon the developers of your derived classes? Perhaps there is a better way to achieve what you want.
But more generally: I am not sure that your hierarchy is sensibly designed in the first place. When I see a method GiveBonus on an Employee, I assume that this means that "an employee can give a bonus", not "an employee can receive a bonus". Surely a manager gives a bonus and an employee receives a bonus. I think you might be making the employee hierarchy do too much.
You can not, unless you make SalesPerson abstract or change the hierarchy.
How about:
Employee*
^
|
SalesPersonBase* (have all the code except GiveBonus)
^ ^
| |
SalesPerson PTSalesPerson
Both Employee and SalesPersonBase are now marked as abstract.
However, if you require a PTSalesPerson to not only inherit behavior, but also inherit the is-a relationship (a PTSalesPerson is also a SalesPerson), then you have no way of forcing this.
Note, the above text is only valid if you only consider compile-time checks. In other words, if you want the compiler to complain if you haven't added an override to the PTSalesPerson class, you cannot do that, unless you do what I outlined above.
However, there's nothing stopping you from using reflection to examine the methods at runtime, and throw an exception if the method in PTSalesPerson is not explicitly overridden there, however I would consider that a hack.
This is a very old thread but the answer given on this question can be usefull.
You can force a derived class to have its own implementation of a virtual method/property.
public class D
{
public virtual void DoWork(int i)
{
// Original implementation.
}
}
public abstract class E : D
{
public abstract override void DoWork(int i);
}
public class F : E
{
public override void DoWork(int i)
{
// New implementation.
}
}
If a virtual method is declared abstract, it is still virtual to any
class inheriting from the abstract class. A class inheriting an
abstract method cannot access the original implementation of the
method—in the previous example, DoWork on class F cannot call DoWork
on class D. In this way, an abstract class can force derived classes
to provide new method implementations for virtual methods.
Declare the class Employee as abstract, the class SalesPerson as concrete (non-abstract), and provide an implementation of GiveBonus() that throws a runtime exception with a message like "Must be implemented by subclasses" for any types or cases which the provided code is not supposed to cover. It's an old Smalltalk practice. I have used it in Java code.
if (GetType() != typeof(SalesPerson))
{
throw new NotImplementedException("Please override in subclasses");
}
// ...proceed with giving SalesPerson a bonus
Use dependency injection. Create a BonusCalculator class:
public abstract class BonusCalculator
{
public abstract decimal CalculateBonus(Employee e)
}
In your base class:
private BonusCalculator Calculator { get; set; }
public void GiveBonus()
{
Bonus = Calculator.CalculateBonus(this)
}
In your implementation's constructor:
public SomeKindOfEmployee()
{
Calculator = new SomeKindOfEmployeeBonusCalculator();
}
Someone implementing a Person subclass now has to explicitly provide it with an instance of a BonusCalculator (or get a NullReferenceException in the GiveBonus method).
As an added, er, bonus, this approach allows different subclasses of Person to share a bonus-calculation method if that's appropriate.
Edit
Of course, if PTSalesPerson derives from SalesPerson and its constructor calls the base constructor, this won't work either.
A WA may be using an "Interface" so you define one like IBonusGiver { void GiveBonus(); }
An then, instead of the abstract method and the overrides, you implement in all your classes this new interface. e.g. PTSalesPerson : SalesPerson, IBonusGiver forcing a new implementation in each class.
You can't using the setup you described. PTSalesPerson will already have an implementation of GiveBonus because it inherits from SalesPerson.
I feel like this indicates that your implementation really has two parts: a partial implementation that goes in the base class, and a missing completion to that implementation that you want in the sub class. Ex:
public abstract class Base
{
public virtual void PartialImplementation()
{
// partial implementation
}
}
public sealed class Sub : Base
{
public override void PartialImplementation()
{
base.PartialImplementation();
// rest of implementation
}
}
You want to force the override, since the initial implementation is incomplete. What you can do is split your implementation into two parts: the implemented partial part, and the awaiting-implementation missing part. Ex:
public abstract class Base
{
public void PartialImplementation()
{
// partial implementation
RestOfImplementation();
}
// protected, since it probably wouldn't make sense to call by itself
protected abstract void RestOfImplementation();
}
public sealed class Sub : Base
{
protected override void RestOfImplementation()
{
// rest of implementation
}
}
If you aren't going to create a SalesPerson instance directly, then the simplest thing to do would be to make SalesPerson abstract and that would force any child classes to implement it instead (or be abstract themselves).
If there is some logic in that method common to all SalesPeople, then you could implement GiveBonus on SalesPerson as a template method. Which calls some abstract method required in any subclasses:
Which ever way you decide, the only way to force an implementation in a child class is to make the base class abstract.
The only way i can see of making this work, if you can not make SalesPerson Abstract, is this:
1) in SalesPerson.GiveBonus(...) use reflection to determine if 'this' is a SalesPerson, or a derived class
a) if not a derived class, do current code in SalesPerson.GiveBonus
b) otherwise call GiveBonusDerived. (declare this as virtual, and make the implmentation in SalesPerson throw an exception.)
The draw backs here are, Reflection is slow. No compile time error if GiveBonusDerived isn't declared, etc.
You could always make SalesPerson's implementation throw a NotImplementedException. :V But contractually, no, you can't do that.
This is pretty old, but we have a somewhat similar situation. The base class loads a configuration file and sets up base class defaults. However, the configuration file could also contain default values for inherited classes.
This is how we got the combined functionality.
Base class methods
private void processConfigurationFile()
{
// Load and process the configuration file
// which happens to be an xml file.
var xmlDoc = new XmlDocument();
xmlDoc.Load(configurationPath);
// This method is abstract which will force
// the inherited class to override it.
processConfigurationFile(xmlDoc);
}
protected abstract void processConfigurationFile(XmlDocument document);
Okay, I know this post is old, however, I have recently needed to look this answer up, so for anyone else looking for this: (I am using VS 2012 .net 4.5, so not sure about older versions)
I created an abstract class, and used override on both child classes:
public abstract class Person
{
public string Name { get; protected set; }
public abstract void GiveName(string inName);
}
public class Employee : Person
{
public override void GiveName(string inName)
{
Name = inName;
}
}
public class SalesPerson:Employee
{
public override void GiveName(string inName)
{
Name = "Sales: "+inName;
}
}
Testing:
SalesPerson x = new SalesPerson();
x.GiveName("Mark"); //Name="Sales: Mark"
Employee e = x;
e.GiveName("Mark"); //Name="Sales: Mark"
Employee m = new Employee();
m.GiveName("Mark"); //Name="Mark"
I very much hope my answer will help some people confused by this issue.
Bear with me, but I'll try to re-summarise what is being asked, just to ensure that I am answering the right question. Then I'll give the answer!
I think the essence of the question is: How do I declare a method in an abstract class so that is has an implementation but still requires a derived class to override the method?
C# doesn't appear to support this. If you declare the method 'abstract', it is not permitted to have an implementation (body). But if you declare it 'virtual', a derived class is not forced to override it. C# deosn't allow a method to be marked as both abstract and virtual.
I believe there are many situations where you wish to do this (what is being asked).
The way to solve this riddle is as follows: Declare two methods! One of them is marked 'abstract'; the other is marked 'virtual' and calls the first one somewhere in its body.
This way, the derived class is forced to override the abstract method, but the (partial) implementation in the virtual method can be safely inherited.
So, for example, the Employee method GiveBonus might be declared thus:
public abstract decimal ComputeBonus();
public virtual void GiveBonus() {
decimal amount = ComputeBonus();
if (amount > 0.0) PostBonus(amount);
}
I'll leave the details of PostBonus to the imagination, but the beauty of this approach is that derived classes are forced to override ComputeBonus, yet GiveBonus benefits from the partial implementation provided in the base class. HTH