I am asp.net programmer.i have read the articles of abstract class and interface and i know how to implement it also.but can anybody explain me practically i.e. by referring project scenario where to use abstract class and where to use interface?
I need a very practical or real world project example, so that i can implement it in my project very efficiently?
Thanks in advanced.
I can't give you a practical example straightaway but let me explain the fundamental difference between both things with small examples:
An abstract class is part of a hierarchical structure of classes. That means they are used for inheritance. Interfaces have nothing to do with inheritance. An abstract class means you cannot instantiate it, and all members (fields, methods and constructors) are inherited by subclasses. An interface can only define methods to be implemented.
You should use an abstract class where you have a hierarchical structure that makes sense:
A vehicle can be an abstract class to car and boat, if you only want actual cars and boats to be instantiated. The vehicle can have a maximumSpeed field, which is then inherited. An interface can not define this field.
You should use an interface when you only need the methods. Suppose you are writing a program that interacts with these vehicles ("drive them"), but does not care about the state of these objects, you can define an interface vehicle with a method drive() so that the program can drive all boats and cars, without knowing what they really are.
Finally, a class can implement multiple interfaces. Another example to show the difference, if you can picture your object in real life, think how you would interact with it. Suppose a coffeemaker, it has an on/off buttons. An "abstract coffee machine" does not really make sense. All you need to know is that there is an setOn() and setOff() method.
I personally like to use interfaces when I have to define a characteristic or an ability of an object regardless of what the object is.
In a "real life" example figure out to have 2 classes, Person and Mones (my nick name :D), and 1 interface, IGuitarPlayer.
So, Mones inherits from Person, and if Mones has the ability to play the guitar it implements the IGuitarPlayer interface.
Since examples from projects depend on the domain, which you have to understand first to be able to understand the example, I will abstract it with a cooking example.
Suppose we want to be able to cook pasta with different sauces: we want to handle pasta independently of its sauce in our source code. A first approach could be that of defining an interface IPasta with a method Cook:
public interface IPasta
{
void Cook();
}
Our client code can then cook the pasta independently from the implementation of it: tomato sauce, pesto sauce? You name it, we can cook it:
...
IPasta pasta = GetPasta();
pasta.Cook();
...
Thinking about the problem more carefully, though, we find out that cooking pasta is always the same process, excluding the point where we want to prepare the sauce.
This means that we have a base algorithm for pasta that we can implement independently from any sauce: boil the water, prepare a sauce, take the pasta out of the pot and merge it with the sauce.
public abstract class Pasta
{
public void Cook()
{
BoilWater();
PrepareSauce();
...
}
protected abstract void PrepareSauce();
private void BoilWater()
{
// Boil some water
}
}
public class PastaWithPestoSauce
{
protected override void PrepareSauce()
{
// Prepare pesto sauce
}
}
And our clients will use it like this:
...
Pasta pasta = GetPasta();
pasta.Cook();
...
So we still have an interface, not in C# sense but in the generic sense of a well known public behavior (the public method Cook of the abstract class), but we also managed to spare some code.
Related
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
could some body explain me abstraction and interface in asp.net, C# by taking an apprpriate example...pleasse
i am not understanding it for long
I often find the following sample quite illuminating when it comes to explaining this:
Disclaimer: the code examples are written directly into the text, and may contain errors that I have overseen. Please let me know if you find such errors.
Let's say you have a database with a Customer table, and in your code you have a customer class:
class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
In order to provide a mechanism to get customer data from the database, you need to write some class doing that. This can be placed in something called a repository. Now, we don't want our code to rely too much on what exact database we use. It could be SQL server, it could be a text file. So we want an abstraction layer shielding the code from this knowledge. All we need to know is what such a repository looks like:
public interface ICustomerRepository
{
Customer GetCustomer(int id);
IEnumerable<Customer> FindCustomers(string beginningOfName);
}
We can now implement this interface for the data storage that we use:
public class SqlServerCustomerRepository : ICustomerRepository
{
public Customer GetCustomer(int id)
{
using(SqlConnection connection = new SqlConnection(connectionString))
{
// code to fetch data and populate Customer objects go here
}
}
// implementations of other members of ICustomerRepository
// left out to keep code short. Just imagine they are here :)
}
Finally, when we want to use this code, we can have a factory create the concrete ICustomerRepository implementation to use:
public static class RepositoryFactory
{
public static ICustomerRepository CreateCustomerRepository()
{
return new SqlServerCustomerRepository();
}
}
...and in our code where we need the data:
ICustomerRepository repository = RepositoryFactory.CreateCustomerRepository();
IEnumerable<Customer> customers = repository.FindCustomers("A");
This way, there is no hard coupling between the consuming code, and the particular kind of repository in use (except for in the factory method, but that is the one and only place where this knowledge exists). This makes it easy to replace the concrete repository implementation. This is also useful for testing, where you can easily create a mock repository returning hard coded results for given input, so that you can unit test the code that needs data from the repository.
Well abstract classes and interfaces are not strictly asp.net technic they are OOP concept.
Interface
An interface is like a class but all the methods and properties are abstract. An Interface cannot be instantiated like abstract class. All the methods and properties defined in Interface are by default public and abstract.
Interface generally refers to an abstraction that an entity provides of itself to the outside. Interface can help in separating the methods for external and internal communication without effecting in the way external entities interact with the type..
Example:
If you have interface IDoSomething { void Do(); }
The class that implements the interface must provide a body for Do() method e.g.
class SomeClass : IDoSomething
{
public void Do()
{
//body of the method
}
}
The advantage of this is when you make something that need only Do method you pass the interface not the class.
public static void SomeMethod(IDoSomething obj)
{
obj.Do();
}
Now SomeMethod(IDoSomething obj) will work with any class that implements IDoSomething
Abstract Class
An abstract class is a class with at least one method defined as abstract. This type of class cannot be instantiated. An abstract class can have one or more abstract methods and properties and other methods and properties like normal classes.
The idea is the same but in abstract class you can have methods with implemented logic, fields and so on.
Abstraction
Abstraction is the process of hiding how the object is working, and its only showing the information of the object the way we can understand it. Means it represent the essential details with out showing ground details. We putting all variables and method in a class which are necessary.
Eg: Employee and Patient.
Company interested to fill about the Employee details like Name, Address, Qualification, DOB, Age, Mobile, Marks, Experience etc
Hospital interested to fill about the patient details like Name, DOB, Height, Weight, Age, Address, Mobile, Blood Group etc.
Both Company and hospital interested to fill some common fields like Name, Age, DOB, Address, Mobile etc. So we can create a class which consist of common thing that is called abstract class. This class wont be complete but can inherit by other class.
Abstract vs Interface
You cannot create an object of abstract class , but can make derivations of this.
An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.
An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must override to its derived class.
Defining an abstract class with all the abstract members is similar to defining an interface. i.e we can say an interface is an abstract class with all the abstract members
Classes may inherit from only one base class, so if you want to use abstract classes to provide polymorphism to a group of classes, they must all inherit from that class.
Abstract classes may also provide members that have already been implemented. Therefore, you can ensure a certain amount of identical functionality with an abstract class, but cannot with an interface.
Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.
1). If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
2). If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
3). If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
4). If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
I know that my this question may sound pathetic to you but as a beginner in .NET, it means a lot to me.
I just want to know that how can I utilize the concept of Abstract class, virtual class etc. in my shopping cart website. I have read the tutorial out there on internet and I saw some examples too, but those examples are so general that they dosen't fit into real world scenerio like I am searching for a shopping website. Same questions again and again comes to my mind that why to made a class only to give the declaration of methods and property.
I understand that most of you are Gurus of .NET and have ample knowlesge in it but if you could just help me out in thinking the logic behind this i'll be very greatfull.
If possible, please recommend me nice books for asp.net design patterns, from which I can learn design patterns.
Thanks in advance
Your one stop resource and guide is Head First - OOAD.
alt text http://i36.tinypic.com/8y6luo.jpg
If you can't see why to use them then don't for now. Never use a design pattern just for the sake of it.
As for their purpose however, imagine that you want to allow different types of products, but you never have something that is just a "Product" - it's always something specific like a "Book" or "Car". In that case you can put the common properties in an abstract Product class like this:
public abstract class Product
{
/* Abstract Price allows Car/Book to apply their own category discounts */
public abstract decimal Price { get; }
public string Title { get; }
public void AddReview(int userId, string reviewText)
{
/* Add review */
}
public abstract List<Product> Recommendations(int userId);
}
which your Book and Car classes can then extend.
Here is a good design patterns book with examples in C#.
C# 3.0 Design Patterns
Its not ture that for every desing you have to use Abstarct class or define virtual methods.
Basically virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class, and Abstarct keyword enables you to create classes and class members solely for the purpose of inheritance—to define features of derived, non-abstract classes
In your case you can have an abstract class called CartItem which works as a base class for all the types of items you are supposed to support in you cart. All types of items will inherit the CartItem class. You can’t directely create the instance of CartItem class but you can use this as a reference to achieve the Polymorphism.
You can define some concrete methods/properties like ItemId, ItemName, Price etc in the CartItem class which are common to all the types of items and you can also define some of the methods a virtual for which you have a default implementation but the child classes can override the implementation.
if we can access the private members through setters and getters then what is the use of private?
You need the private to enforce Encapsulation. It is one of the fundamental paradigm of Object Oriented programming to keep the implementation of something separate from the interface. This reduces the coupling between your different program parts and in the long run make it more maintainable.
Take the following example :
class toto {
private String someThing;
public String getSomething();
public void setSomething(String Something);
}
If you change above to simply put someThing public, sure you have less code, but if one day that someThing needs to change to a more complex object for some new functionality while the old code could still work fine with a string then you need to change everything. By isolating the internal representation of someThing you can evolve your system much more easily
class toto {
private ComplexSomeThing someThing;
public String getSomething(){ someThing.toString();}
public void setSomething(String something){ something = new ComplexSomeThing(something);}
public ComplexSomeThing (getComplexSomething();
public void setComplexSomething(ComplexSomething someThing);
}
There are other reasons that makes encapsulation a Good Thing (tm), this is just a silly example to illustrate the point.
EDIT
There is somewhat of a debate right now as to using protected vs private or to use concepts akin to properties in some languages (Delphi, C#) rather than getters and setters (as in Java).
Protected rather than private will allow easier changes by the clients of the code but it does expose the innards of your system more so there is a balance to strive for between usability of the API and it's maintainability. However the basic principle of encapsulation remains.
Whatever the option chosen one still needs to expose functionality that is coherent and on the same level of abstraction and hide the gory details of how this is done.
To me the debate is not to declare a jihad against private but to find a way to provide extensibility and flexibility while not breaking the coherence of the API.
Here some interesting reading about private if you want to dig further. However I must stress that before forming an opinion about private you should really master the concepts of encapsulation and polymorphism, their apparent simplicity does hides some subtle complexities.
Because the getters and setters can act as a proxy. They make it so that you can hide the actual insides of the class, and only let the outside classes access the data through methods. Allowing you to treat the inners of the class however you want.
Just because your getter/setter is named getName() and your property is called name, doesn't mean it will always be that way.
What if you wanted to change the variable to be fullName. If you directly accessed public variables, the change would break a lot of code. Instead, you can simply remap where getName() retrieves its data from.
One of my best examples of this is my own URL class, where I allow for creating and manipulating a URL. If you want to set the scheme, you can get $obj->setScheme(). However, you don't know whether I am manually making the string every time you change the URL, whether I am storing them as separate parts. This gives me flexibility as I can store your data however I want to.
Furthermore, I can preform manipulations on the data before storing it. In my URL class, I assume that all schemes and host names are lowercase. I can standardize this by converting all strings saved via setHost() to lowercase, and then storing them. If I used a public variable, you would have to assume that the client that put the data in was correctly storing it.
They can also validate information that is being passed in to make sure that it is valid data, and cause an error if it isn't.
No one forces you to put in getters and setters for every variable. Indeed, blindly using private members + dummy getters & setters for every variable is pointless, even though many "object oriented encapsulation" tutorials do this all the time for some reason. For one thing, such encapsulation is no encapsulation from concurrency viewpoint.
I think what you really want to understand is why we use public properties with private backing fields, instead of just using public fields. There are several questions on SO like this; here's one:
What is the difference between a Field and a Property in C#?
I think you have good answers so far (information hiding and all that). Just want to add a suggestion about using setters.
As you mentioned using accessors makes private variables a bit pointless and in some environments performance consequence of using getters and setters just makes it worthless.
On the other hand if you don't have such concerns, I think using getters isn't so bad, but you should think twice before using setters. They make your object mutable which is especially hard to maintain in concurrent environments.
What's the best object layout in ASP.net or at least.. what are the advantages and disadvantages of either case:
Public Class Dog
Public Breed as String
Public Type as String
Etc....
OR the use of properties and keeping variables private
Somewhat of a debate among our team about it. Just wanted to hear thoughts.
Never expose fields directly.
Use properties with private backing fields. This allows you to change implementation and to encapsulate logic around getting/setting them.
See what the Visual Basic Team have to say on this.
Also, read about the differences between fields and properties.
Just as the title asks, when should a trigger in your head go off signifying "Aha! I should use the factory pattern here!"? I find these moments will occur with many other design patterns, but never do I stop myself and think about this pattern.
Whenever you find yourself with code that looks something like this, you should probably be using a factory:
IFoo obj;
if ( someCondition ) {
obj = new RegularFoo();
} else if ( otherCondition ) {
obj = new SpecialFoo();
} else {
obj = new DefaultFoo();
}
The factory pattern is best employed in situations where you want to encapsulate the instantiation of a group of objects inside a method.
In other words, if you have a group of objects that all inherit from the same base class or all implement the same interface that would be an instance where you would want to use the factory pattern (that would be the "pattern" you would look for).
I can think of two specific cases that I think of the factory pattern:
When the constructor has logic in it.
When I don't want the application to worry about what type gets instantiated (eg, I have an abstract base class or interface that I am returning).
Quoted from GoF:
Use the Factory Method pattern when
a class can't anticipate the class of objects it must create
a class wants its subclasses to specify the object it creates
classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.
I highly recommend the GoF book. It has a section on the applicability of each of the 23 patterns it covers.
Are you talking about Factory Method or Abstract Factory?
The basic problem that both solve is letting clients specify the exact class that framework code constructs. For example, if you provide an interface, that clients can implement, and then in your code have something like:
IMyInterface x = new ConcreteClass();
There is no way for clients to change the exact class that was created without access to that code.
A Factory Method is a virtual method that constructs a concrete class of a specific interface. Clients to your code can provide an object that overrides that method to choose the class they want you to create. It might look like this in your code:
IMyInterface x = factory.Create();
factory was passed in by the client, and implements an interface that contains Create() -- they can decide the exact class.
Abstract Factory should be used if you have hierarchies of related objects and need to be able to write code that only talks to the base interfaces. Abstract Factory contains multiple Factory Methods that create a specific concrete object from each hierarchy.
In the Design Patterns book by the Gang of Four, they give an example of a maze with rooms, walls and doors. Client code might look like this:
IRoom r = mazeFactory.CreateRoom();
IWall nw = mazeFactory.CreateWall();
IWall sw = mazeFactory.CreateWall();
IWall ew = mazeFactory.CreateWall();
IWall ww = mazeFactory.CreateWall();
r.AddNorthWall(nw);
r.AddSouthWall(sw);
r.AddEastWall(ew);
r.AddWestWall(ww);
(and so on)
The exact concrete walls, rooms, doors can be decided by the implementor of mazeFactory, which would implement an interface that you provide (IMazeFactory).
So, if you are providing interfaces or abstract classes, that you expect other people to implement and provide -- then factories are a way for them to also provide a way for your code to construct their concrete classes when you need them.
Factories are used a lot in localisation, where you have a screen with different layouts, prompts, and look/feel for each market. You get the screen Factory to create a screen based on your language, and it creates the appropriate subclass based on its parameter.