Solved

Concrete vs Abstract vs Interface simple example looking for that makes sense.  No links please

Posted on 2013-01-24
8
387 Views
Last Modified: 2013-01-28
Hello all,

Can someone provide in very simple terms best with an example the difference between the three of these?  I use them throughout my coding but I get confused sometimes where and when to use etc.   Let me know how far off I am here:

using System;

namespace SportsStore.WebUI.Models
{
    public class PagingInfo
    {
        public int TotalItems { get; set; }
        public int ItemsPerPage { get; set; }
        public int CurrentPage { get; set; }
        public int TotalPages 
        {
            get { return (int)Math.Ceiling((decimal)TotalItems / ItemsPerPage); }
        }
    }
}

Open in new window


This seems to be a 'concrete' class.  I can create an instance of this concrete class and assign the variables such as:
PagingInfo pagingInfo = new PagingInfo();

An abstract class is a little more confusing to me.   Is this simply a base class where I can inherit it in a class as a subclass?   For example, maybe I have a user class that contains username, building, group etc. I can inherit this as a subclass in my class to gather the values?

Interface I have always struggled with but this is what I should use where I want to use all the methods and properties.  This also seems to be the best thing to use when working with dependency injection and moq unit testing etc.  Still trying to get a full grip on this for a long time now.   Is an interface really just like an abstract class where you can implement the methods but don't really need to see what they are doing?

Thanks all hope this helps me a little more.
0
Comment
Question by:sbornstein2
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 38814673
A class (you call concrete) is one you can create an instance of.  It can also be used as the base of another class.

An abstract class is one you can NOT make an instance of.  It is used for common code that is shared between the derived classes.

An interface is a specification of methods exposed.

A class can inherit from ONE class but MANY interfaces.
0
 
LVL 42

Accepted Solution

by:
sedgwick earned 150 total points
ID: 38814708
lets take the shapes example, you have class Triangle, class Square and so on.

now, when you think about implementation, you understand that each of the shapes classes should have list of points, right?
the triangle will have list of 3 Point instances and Triangle will have 4.

so instead of declaring  List<Point> as a member in each class shape, you gonna have abstract class which has it as protected member, which allows the concrete classes access to it.

so here one example of using abstract.
the 2nd example will be shared implementation, for instance, if you want to save the shape information to a file.
you do not need to have a separate implementation in each shape, instead you can use a SaveShape function in the abstract class which does that.

the function creates a file and write the coordinates of the shape.

so basically we have something like:
inerface IShape{
void ClaculateArea()
void SaveShape()
}

abstract class BaseShape:IShape{
protected string _shapeName;
protected List<Point> _points;
public BaseShape(shapeName, IEnumerable<Point> points){
_shapeName=shapeName;
_points=new List<Point>(points);
}

public SaveShape(string file){
var lines = _points.Select(point=>String.Format("X-[{0}], Y-[{1}]", point.X, point.Y)).ToArray();
var output = string.Join(lines, Environment.NewLine);
File.WriteAllText(file, output);
}
}

//the ctor of each shape calls the abstract base class ctor with the shape name and coordinates.
class CSquare{
public CSquare(IEnumerable<Point> points):base("Square", points){
}
}
class Triangle{
public CSquare(IEnumerable<Point> points):base("Triangle", points){
}
}

Open in new window


to allow consumers use concrete objects without expose the class it self, we can create ShapeCreator which accept enum shape and return new shape instance as IShape.

public static class ShapeCreator{
public enum ShapeType{Square,Triangle};
public static IShape Create(ShapeType shapeType, IEnumerable<Point> points){
switch(shapeType){
case ShapeType.Square:return new Square(points);break;
case ShapeType.Trianglenew Triangle(points);break;
}
}
}

Open in new window


so to create a shape you use the following:

IShape square = ShapeCreator.Create(ShapeCreator.ShapeType.Square, new Point[]{
new Point{X=1,Y=1},
new Point{X=1,Y=5},
new Point{X=5,Y=1},
new Point{X=5,Y=5},
});

double area = square.CalculateArea();
square.SaveShape("C:\square.log");

Open in new window

0
 

Author Comment

by:sbornstein2
ID: 38814772
sedg where is CSquare being implemented and doesn't the interface IShape both methods need to be used?   In BaseShape you inherit IShape, you implement the SaveShape method btu I don't see CalculateArea being implemented?
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 38814821
CalculateArea is implemented differently for rach shape so theBaseShape declares it as abstract which forces the shapes implement it in their classes.
Public abstract class BaseShape:IShape{

Public abstract double CalculateArea();
}

Public class Square: BaseShape{
public virtual double CalculateArea(){
//calculate square based on _points Member
}
}

Open in new window

0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 74

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 100 total points
ID: 38815718
0
 

Author Closing Comment

by:sbornstein2
ID: 38825322
these really helped thanks guys.  Kaufmed thanks that link also clarified some things for me.  I just need to get used to when to use certain things.  It seems for dependency injection and moq unit testing interfaces is the best way to go when I can use them.   Thanks
0
 

Author Comment

by:sbornstein2
ID: 38825337
Kaufmed I am reading your other links as well.  Seriously a huge help to me thank you.   That interface response was something I have been looking for a long time now.  It explains it in simple but terms that make a lot more sense now.   Thanks for these links really really helpful.
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 38829384
No problem. Glad they were useful  = )
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

How to remove superseded packages in windows w60 or w61 installation media (.wim) or online system to prevent unnecessary space. w60 means Windows Vista or Windows Server 2008. w61 means Windows 7 or Windows Server 2008 R2. There are various …
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now