I could not find this question anywhere. Based upon my understanding, Inheritance should/might be the subset of Abstraction.
First of you should be aware, that here is always some leeway in interpreting such terms and concepts. Below is my take on it.
Abstraction is the concept while inheritance is a technical realization.
Abstraction in general refers to the leaving out of (unnecessary) details. The opposite direction is concretization. Generalization is also often used in this context and basically means the same as abstraction.
In the context of computer science this can be used to describe several ideas:
One is the modelling of domain concepts. As in the class Car is an abstraction of real world automobiles. It uses an engine and four wheels to transport 1-5 people. Obviously this is nowhere near the informational density to describe a real car, but it may very well be all that is needed for the context of this application.
An other is to use it to describe the conceptual relation between multiple domain entities: A Car is a Motorvehicle. A Bus is also a Motorvehicle. Both are used to transport people. The Motorvehicle is the abstraction of both Car and Bus. It describes the idea of transporting people, while leaving out the detail of how many.
A third is the difference between an interface and an implementation. The interface abstracts the implementation by hiding the implementation details and only representing the surface area with which one may interact.
Inheritance is one method of realizing abstractions in code. It describes the process of taking a base class (this is the more general or abstract thing), inheriting all of its features/properties/behavior/meaning and adding some more details (or overriding some of the existing) to create the derived class (this is the more concrete thing).
First, When you mark a class as abstract you cannot create an instance. Abstract classes are used to be inherited only.
But when you inherited from a non abstract class you can create instance from both of derived and base classes. So you can say abstract classes are used to generate new types, to be inherited not to create instance !
This is also somehow related polymorphism.
For example you have a base Employee class like below:
public class Employee
{
public string Name { get; set; }
public double Salary { get; set; }
public void IncreaseSalary(double rate)
{
this.Salary += (this.Salary * rate / 100);
}
}
Now when we create SalesRepresentative class like below we should inherit it from Employee because SalesRepresentative is an Employee.
public class SalesRepresentative : Employee
{
public double AnnualSalesAmount { get; set; }
}
Now SalesRepresentative object has IncreaseSalary method because it is inherited from Employee. But in generally Sales Representatives' and Employee's Salaries are increased by different ways for example according to their AnnualSalesAmount.
In this case you should be able to change method code of IncreaseSalary from SalesRepresentative but you can't. Actually now you are across with Polymorphism
Now Let's come to abstraction. If you want to change the default code of IncreaseSalary from inherited class there are 2 choices. First marking the method as Virtual. And the second one is marking it as abstract.
The difference is If you mark it as virtual. You don't have to implement it in SalesRepresentative but If you mark it as abstract you have to implement it and you should forget an abstract member can only be in abstract classes. Examine the example below:
public abstract class Employee
{
public string Name { get; set; }
public double Salary { get; set; }
public abstract void IncreaseSalary(double rate);
}
public class SalesRepresentative : Employee
{
public double AnnualSalesAmount { get; set; }
public override void IncreaseSalary(double rate)
{
if (this.AnnualSalesAmount > 100000)
{
this.Salary += (this.Salary * (rate + 5) / 100);
}
else
{
this.Salary += (this.Salary * rate / 100);
}
}
}
Related
I'm not really sure what looks better or when do I really use in abstract classes and properties, or when to use non abstract properties. I'll try to make a simple example. Let's say I have this:
abstract class Human
{
public GenderType Gender { get; set; }
public string Name { get; set; }
public Date Born { get; set; }
public bool IsNerd { get; set; }
abstract public void Speak();
abstract public void Sleep();
abstract public void AnoyingPeopleOnStackOverflow();
//... so on
}
class Peter : Human
{
//Peter is special, he got a second name
//But thats all, everything else is the same as like on other humans
public string SecondName { get; set; }
//...override abstract stuff
}
Is this alright? As I understood, I don't have to use an abstract property if I dont want to override it. And in this situation it would be ok, just the methods like Speak, Sleep and so on should be abstract.
Now, if this is ok, when would or should I use an abstract property?
Use an abstract property when you have no default implementation and when derived classes must implement it.
Use a virtual property when you have an implementation in the base class but want to allow overriding.
Use the override keyword to override a member. Mark the member as sealed override if it should not be overridden again.
Don't mark the property as abstract or virtual if you don't want it to be overridden.
Use the new keyword to hide a non-abstract, non-virtual member (this is rarely a good idea).
How to: Define Abstract Properties
I find that abstract properties often occur in a design which implies that they will have type-specific logic and/or side effects. You are basically saying, "here is a data point that all subclasses must have, but I don't know how to implement it". However, properties which contain a large amount of logic and/or cause side effects may not be desirable. This is an important consideration, though there is no fixed right/wrong way to do it.
See:
Should Properties have Side Effects
CA1024: Use properties where appropriate
Personally, I find that I use abstract methods frequently but abstract properties rarely.
I know what I want them to do, I don't care how they do it: Interface.
I know what I want them to do, I don't care how they do some of it, but I've firm ideas on how they'll (or at least most of them) do other bits: Abstract class.
I know what I want them to do, and how most of them will do it: Concrete class with virtual members.
You can have other cases such as e.g. an abstract class with no abstract members (you can't have an instance of one, but what functionality it offers, it offers completely), but they're rarer and normally come about because a particular hierarchy offers itself cleanly and blatantly to a given problem.
(Incidentally, I wouldn't think of a Peter as a type of Human, but of each peter as an instance of human who happens to be called Peter. It's not really fair to pick on example code in this way, but when you're thinking about this sort of issue it's more pertinent than usual).
Abstract members are simply virtual members that you have to override. You use this for something that has to be implemented, but can't be implemented in the base class.
If you want to make a virtual property, and want that it has to be overridden in the class that inherits your class, then you would make it an abstract property.
If you for example have an animal class, its ability to breathe would not be possible to detemine just from the information that it's an animal, but it's something that is pretty crucial:
public abstract class Animal {
public abstract bool CanBreathe { get; }
}
For a fish and a dog the implementation would be different:
public class Dog : Animal {
public override bool CanBreathe { get { return !IsUnderWater; } }
}
public class Fish : Animal {
public override bool CanBreathe { get { return IsUnderWater; } }
}
Use abstract when all sub-classes have to implement the method/property. If there's no need for each and every sub-class to implement it, then don't use it.
As for your example, if SecondName is not required for each person, then there's no need to make an abstract property in the base class. If on the other hand, every person does need a second name, then make it an abstract property.
Example of correct usage of an abstract property:
public class Car
{
public abstract string Manufacturer { get; }
}
public class Odyssey : Car
{
public override string Manufacturer
{
get
{
return "Honda";
}
}
}
public class Camry : Car
{
public override string Manufacturer
{
get
{
return "Toyota";
}
}
}
Making Maker abstract is correct because every car has a manufacturer and needs to be able to tell the user who that maker is.
An abstract property would be used where you want the class to always expose the property, but where you can't pin down the implemetation of that property - leaving it up to/forcing the inheriting class to do so.
There's an example here, where the abstract class is named Shape, and it exposes an abstract Area property. You can't implement the Area property in the base class, as the formula for area will change for each type of shape. All shapes have an area (of some sort), so all shapes should expose the property.
Your implementation itself looks just fine. Was trying to think of a sensible example of an abstract property for a Human, but couldn't think of anything reasonable.
Let's review some entities:
Company;
Collaborator;
Chief;
Subordinate workers.
There are some rules:
Collaborator could be one of these: Sales, Manager,
Employee;
Sales and Manager could have subordinate workers (of any type decribed in the 1st rule);
Sales, Manager, Employee could have chief;
Each role has its own Salary
calculation method.
So the target is to create flexible & reusable class hierarchy.
First thing that confuses me is "can have" phrase. Should it be implemented as a composition? If it is said "can have as many" should it be a composition with list of objects?
Should I create abstract class Collaborator and then inherit from it 3 other types or there is more smart way?
What is the best way to tie all the entities together and have good reusable assembly?
"Can have" and the fact that its followed by "workers", tells me this is a "has a" relationship (composition) with a 0 to many relationship (so a list as you mention that could be empty)
An abstract class Collaborator seems reasonable.
Can have is represented in UML as (0..*) which means either 0 or more, yes composition with a list of objects would be good, use collections not an array.
Collaborator is an Abstract class since there will be no instances of Collaborator itself. Inheriting the 3 types of Collaborator is the best way I guess.
I have to add that, if you only have one company in your project, you need to implement the Singleton design pattern.
About the Salary use virtual method and override it.
I hope this is not your homework ;)
I find the question poorly formulated, the design can change severly by just adding small extra information.
Based on what you wrote, I might consider creating the following classes ('-' means extends):
Company
AbstractCollaborator (Chief member, CalculateSalary() { return base + AdditionalSalary() }, abstract AdditionalSalary())
- Chief
- AbstractLeader ( List subordinates )
-- Sales
-- Manager
- Employee
Chief would have no chief set for itself. I would try to prevent using virtual functions, and try using abstract functions instead.
Another option would be to simply using one class. It's all nice and well that only Sales or Manager can have subordinates, but in a real world situation it might be necessary for anyone to have subordinates. The function of any type of employee could simply be specified by a enum value instead.
It all depends greatly at where you are going with this ...
I guess the answer to this question is subjective and would change depending on your needs but this is how I would implement it:
public class Company {
public List<Collaborator> Collaborators { get; set; }
}
public abstract class Collaborator {
public Collaborator(Company company) {
company.Collaborators.Add(this);
}
public virtual Decimal Salary(object value);
public Company Company { get; set; }
}
public class Sales : Collaborator {
public override Decimal Salary(object value) {}
public List<Collaborator> Subordinates { get; set; }
public Collaborator Chief { get; set }
}
public class Manager : Collaborator {
public override Decimal Salary(object value) {}
public List<Collaborator> Subordinates { get; set; }
public Collaborator Chief { get; set }
}
public class Employee : Collaborator {
public override Decimal Salary(object value) {}
public Collaborator Chief { get; set }
}
This code has not been tested.
Can someone explain the exact use of interfaces in C#?
Has msdn not been helpful on this?
http://msdn.microsoft.com/en-us/library/87d83y5b.aspx
This has been discussed so many times here in the past that it is hard to pick any one duplicate for this question.
To save the time of repeating what has been said before, try this search, and start going through the results.
Imagine the the situation of having a factory that creates cars. You know that every vehicle has an engine and can be started, so you have the following:
interface IVehicle
{
Engine vehicleEngine { get; set; }
bool StartEngine();
}
Now, the factory makes an array of other vehicles, so for instance a truck and a normal car:
public Car : IVehicle
{
// MUST implement vehicleEngine and StartEngine:
public Engine vehicleEngine { get; set; }
public bool StartEngine()
{
// Cars needs to do xyz to start
}
public int MaxNumberOfPassenger { get; set; } // Specific to Car
}
and then:
public Truck : IVehicle
{
// MUST implement vehicleEngine and StartEngine:
public Engine vehicleEngine { get; set; }
public bool StartEngine()
{
// Trucks needs to do abc to start
}
public int MaximumLoad { get; set; } // Specific to Truck
}
This therefore forces all vehicles to implement specific members to fall under the category of a vehicle, but then can also be specialized with their own distinct members.
In the most simple terms, an Interface expresses what one, or more classes can do, although the implimentation may vary across the various classes.
Polymorphism
You can use 2 classes that implement the same interface without having to know exactly which concrete class it is. It aids in keeping code loosely coupled.
An interface defines the minimum requirements that a class that can be instantiated must implement. It expresses this through methods.
For instance, an interface could define a function called Foo which takes an integer and returns a boolean:
public interface ICanFoo
{
bool Foo(int number);
}
Any class which implements this interface must also implement this method:
public class Fooable : ICanFoo
{
public bool Foo(int number)
{
// do something
}
}
The implementation within the method is up to the specific classes which are implementing the interface.
By using interfaces you no longer care about implementation are compile time, but rather specification. You can call it like this:
ICanFoo myFooable = ...
bool success = fooable.Foo(4);
The actual type of fooable can be any class that implements ICanFoo since you know that ICanFoo will always define a method implementation for the Foo method.
greetings. i have the following class:
public class Ship
{
public enum ValidShips
{
Minesweeper,
Cruiser,
Destroyer,
Submarine,
AircraftCarrier
}
public enum ShipOrientation
{
North,
East,
South,
West
}
public enum ShipStatus
{
Floating,
Destroyed
}
public ValidShips shipType { get; set; }
public ShipUnit[] shipUnit { get; set; }
public ShipOrientation shipOrientation { get; set; }
public ShipStatus shipStatus { get; set; }
public Ship(ValidShips ShipType, int unitLength)
{
shipStatus = ShipStatus.Floating;
shipType = ShipType;
shipUnit = new ShipUnit[unitLength];
for (int i = 0; i < unitLength; i++)
{
shipUnit[i] = new ShipUnit();
}
}
}
i would like to inherit this class like so:
public class ShipPlacementArray : Ship
{
}
this makes sense.
what i would like to know is how do i remove certain functionality of the base class?
for example:
public ShipUnit[] shipUnit { get; set; } // from base class
i would like it to be:
public ShipUnit[][] shipUnit { get; set; } // in the derived class
my question is how do i implement the code that hides the base class shipUnit completely?
otherwise i will end up with two shipUnit implementation in the derived class.
thank you for your time.
ShipPlacementArray deals with only one ship. but the array reflects the directions the ship can be placed at.
what i would like to know is how do i remove certain functionality of the base class?
You don't. This is not the point of inheritance. The point of inheritance is to inherit the base class functionality -- all of it -- and adding/changing stuff. It's for "is-a" relations, e.g., "a car is a vehicle."
my question is how do i implement the code that hides the base class shipUnit completely?
It sounds like you want ShipPlacementArray to be a wrapper, or container, of multiple Ship objects. This does not seem like a case where inheritance should be used.
Ask yourself the question: "is a ShipPlacementArray a kind of Ship?"
In my experience, every time I've wanted to remove a property from a class in an inherited class, my class design was flawed. One way to solve this problem would be to create a new base class without the ShipUnit property and then inherit that base class two times, once for your concrete Ship type and once for your concrete ShipPlacementArray type. In both subclasses you could implement ShipUnit as you need to.
You cannot make members of a base class disappear in a derived class. In certain instances, you can mask or hide the base members by using the new keyword on your hiding member in the derived class, but the user will always be able to cast your object back to the base class (base)instance_of_derived and access the base class's members.
So, for example, you can do in your derived class:
public new ShipUnit[][] shipUnit { get; set; }
But then I can do:
((Ship)ShipPlacementArray_instance).shipUnit
And this will reference the original shipUnit. Thus, you can "hide" the member but you cannot disable its functionality or accessibility.
With C#'s new modifier you can hide an inherited member from a base class member.
Check out this page for reference.
In additoin to the other excellent answers, as an aside I'd say you may find encapsulation to be a better option. Often I used to at first think I wanted to inherit from a class, and later found that I really wanted to encapsulate it. You do this by simply declaring a new instance of the original class in a private field. You then create public properties and function that simply call the original class like the below, giving you a fine grain of control over what gets exposed. This also is a way to side step the disadvantages of inheritance such as added complexity and inability to perform multiple inheritence(for good reason):
class SomeNew
{
private SomeOld someOld = new SomeOld();//could have done this in constructor instead
public DoSomething()
{
someOld.DoSomething();
}
}
I don't know if this is just a contrived example, or an actual problem. But, I would say that the inheritance in this case isn't desired. You have Ship and ShipPlacementArray. The "Array" at the end makes it sound more like its, well, an array data type. So taking that away, you have ShipPlacement.
That sounds to me like its a location somewhere, so maybe it should be a member of the Ship class?
"Favor object composition over class inheritance" - If you are looking for new behavior from the base class, then it doesn't seem like you'd want to inherit anyway because they are different types.
Perhaps Ship and ShipPlacementArray should inherit a common interface, but certainly not from a common base class. Anywhere you'd need to use either you could use the interface - but where you needed your ShipUnit matrix, you'd use the ShipPlacementArray type explicitly.
you can use the "new" operator.
as in
public new ShipUnit[][] shipUnit { get; set; } // in the derived class
You can use the new keyword, like this:
public new ShipUnit[][] shipUnit { get; set; }
I don't fully understand what you want to model with the inheritance but I am quite sure it is the wrong tool. I assume aggregation or composition are what you need.
you can use the new keyword or add virtual on the declaration on the base class and override it on the derived class.
UPDATE:
So pretty much everyone here has told me that I just need to start all over again on how I designed my classes (thank you folks for your excellent answers by the way!). Taking the hint, I started doing extensive reading on the strategy pattern. I want to create behavior classes (or strategy classes) that inherit from an abstract base class or classes. The Candidate class would then have properties w/ the different abstract base class/classes as the Type for the behaviors or strategies. maybe something like this:
public abstract class SalaryStrategy {
public abstract decimal Salary { get; set; }
public abstract decimal Min { get; set; }
public abstract decimal Mid { get; set; }
public decimal CompaRatio {
get {
if (this.Mid == 0) { return 0; }
else { return this.Salary / this.Mid; }
}
}
}
public class InternalCurrentSalaryStrategy {
public override decimal Salary { get; set; }
public override decimal Min {
get { return this.Salary * .25m; }
set { }
}
public override decimal Mid { get; set; }
}
public class Candidate {
public int Id { get; set; }
public string Name { get; set; }
public SalaryStrategy CurrentSalaryStrategy { get; set; }
}
public static void Main(string[] args) {
var internal = new Candidate();
internal.CurrentSalaryStrategy = new InternalCurrentSalaryStrategy();
var internalElp = new Candidate();
internalElp.CurrentSalaryStrategy = new InternalCurrentSalaryStrategy();
var elp = new Candidate();
// elp.CurrentSalaryStrategy can stay null cause it's not used for elps
}
Any comments or suggestions?
ORIGINAL Question:
I am trying to learn and become more proficient at design patterns and principles. I have am currently working on a design for few classes that has stumped me. Here's a very condensed version of the code:
public class Candidate {
public int Id { get; set; }
public string Comments { get; set; }
// lots more properties and behaviors...
}
public class InternalCandidate : Candidate {
public decimal CurrentMid { get; set; }
public decimal CurrentMax {
get { return this.CurrentMin * 1.3m;
}
// lots more properties and behaviors...
}
public class EntryLevelCandidate : Candidate {
public string Gpa { get; set; }
// lots more properties and behaviors...
}
public class InternalEntryLevelCandidate /* what do I inherit here??? */ {
// needs all of the properties and behaviors of
// EntryLevelCandidate but also needs the CurrentMin and
// CurrentMax (and possibly more) in InternalCandidate
}
The InternalEntryLevelCandidate class is primarily an EntryLevelCandidate but needs to share some of the implementations of InternalCandidate. I say implementations because I don't want the implementations to be different or repeated, otherwise I would use an interface for common contracts and have concrete implementations in each class. Some of the implementations of the InternalCandidate properties and behaviors need to be common or shared. I have read about C++ and Ruby mixins, which seem to be something similar to what I want to do. I also read this interesting blog post that discusses an idea for a behavior type where a class would be able to inherit multiple behaviors while still maintaining a single "is a" relationship: http://www.deftflux.net/blog/post/A-good-design-for-multiple-implementation-inheritance.aspx. This seems to convey what I am wanting. Can anyone give me some direction on how I can accomplish this using good design practices?
Immutable data value classes. If any properties in your various Candidate subclasses represent some kind of meaningful data value, create an immutable class for it, with the behaviors you need. Each of your distinct Candidate subclasses can then use the data type, but your code is still encapsulated in the data classes.
Extension methods. These could be overloaded to work with any classes.
I'd avoid the decorator pattern and stick with compiled/reflectable functionality.
Composition. Develop the unique behaviors in separate classes right away, and build your Candidate classes around them, rather than writing unique behaviors in your Candidate classes and trying to pull out their functionality for use in related classes later.
Depending on how you use the classes, you could also implement and make use of explicit and implicit conversion operators to a related type, so instead of reimplementing interfaces (which you wanted to avoid), you could actually cast your object into the type/implementation you need for whatever purpose.
Another thing I just thought of, related to that last paragraph, is to have a leasing system, where your class spawns and object of the appropriate type, allows it to be manipulated, then consumes it later to assimilate the updated information.
Here's a scholarly paper on the subject that I think is pretty interesting (PDF link).
But, I think you are trying to impose business logic in your generalizations. You happen to know that an InternalCandidate will never have his GPA looked at. But, an InternalCandidate certainly has a GPA. So, you have cracked out this strange guy called an InternalEntryLevelCandidate because you happen to know that you want to look at this guy's GPA. Architecturally, I think the EntryLevelCandidate is incorrect. I would add a "Level" concept to a Candidate and give him a GPA. It's up to the business logic to decide if they look at the GPA or not.
Edit: Also, Scott Meyers does a great job of dissecting this issue in his books.
Disclaimer:
In my experience needing multiple inheritance is the exception rather than the rule, careful design of class hierarchies can usually avoid needing this feature. I agree with JP that this requirement could be avoided in your sample.
Back to the question, there is no clean solution, however you have a few options:
Use extension methods, has the disadvantage that right click Resolve does not works, also some people really dislike these puppies.
Create an aggregate object that holds and instance of each class you want composited, re-implement stub methods that delegate.
Define an interface for each behavior and have the methods in the base check if this is IInterface before executing the behavior. (allows you to pull behavior definitions to the base)
Near duplicate:
Multiple inheritance in C#
I agree that inheritance doesn't seem to be the right thing here. I'm not sure that I know the perfect answer, but perhaps the Decorator pattern is appropriate.
Another, more esoteric idea is to think about aspect-oriented programming. You can do some pretty amazing things with aspects, but it's a very advanced topic that I still haven't mastered. The kind of folks who have are like Rikard Oberg and his Qi4J cohorts.
I'd just use the Delegation pattern. Ultimately I'd use an interface for each distinct piece of functionality, then have a concrete class as a delegate for each interface. Then your final classes just use the delegates they need and can inherit from multiple interfaces.
public class InternalEntryLevelCandidate : EntryLevelCandidate {
private InternalCandidate internalCandidateDelegate
= new InternalCandidate();
public decimal CurrentMid {
get { return internalCandidateDelegate.CurrentMid; }
set { internalCandidateDelegate.CurrentMid = value; }
}
public decimal CurrentMax {
get { return internalCandidateDelegate.CurrentMax }
}
}