Overriding Base Class abstract methods and hiding them in derived classes - c#

I have two two types of base class;
public abstract class Base
{
public abstract object Work();
}
public abstract class AuthenticatedBase : Base
{
public abstract object Work(T request);
}
The authenticated class does some extra work to check a login beforehand. Then I have different classes extending from both base classes;
public class A : Base
{
public override object Work()
{
// Work here
}
}
public class B : AuthenticatedBase
{
public override object Work(T request)
{
// Work here
}
}
Basically, when I create a new class B that derives from AuthenticatedBase, Visual Studio says I need to implement Work() from the Base class even though I have an alternate implementation in AuthenticatedBase that I am overriding, admittedly with different parameters. What should I be doing so that I don't have to implement the Work() method from the base class in inherited classes?

Implement the parameterless Work method in your AuthenticatedBase and use the "sealed" keyword to stop it from showing on inheritors of AuthenticatedBase.

You have to implement it, there is no way around it. This is the case where multiple inheritance would come in handy.
You could use composition so that B has a reference to an A. Then B.Work() can call A.Work().
Alternatively, implement B.Work() so that it calls B.Work(T). Or even have Base.Work() be a virtual method with the base implementation from A.

Related

Return child type from a method on an abstract class or force two constructors on child [duplicate]

Is it possible to create an abstract method that must return an instance of the derived class? I can do this:
abstract class Base
{
public abstract Base GetObj();
}
class Derived : Base
{
public Derived() { }
public override Base GetObj()
{
return new Derived();
}
}
But I was wondering if there was a way to do it such that Derived::GetObj() is forced to return a Derived?
Thanks.
Using generics should make this possible:
abstract class Base<T>
where T : Base<T>
{
public abstract T GetObj();
}
class Derived : Base <Derived>
{
public Derived() { }
public override Derived GetObj()
{
return new Derived();
}
}
You could even simplify this even more (if all of the derived instances are created with default constructors):
abstract class Base<T>
where T : Base<T>, new()
{
public static T GetObj()
{
return new T();
}
}
class Derived : Base<Derived>
{
public Derived() { }
}
What you have is almost but not quite exactly an abstract factory. I will first say that you should leave it up to the implementers of the derived classes to get it right, or simply trust that they will.
Another answer has shown what is known as the curiously recurring template pattern. It is where you have a base class that tries to use the type system to enforce that derived types use itself at certain input or output positions.
public abstract class Foo<T> where T : Foo<T>
public class Bar : Foo<Bar>
This idea might work in other languages. It works in C# only so far as people use it correctly. With the above definition of Bar, now I can also have
public class Baz : Foo<Bar>
Which is perfectly legal. Bar is a Foo<Bar>, which is all that is required for Baz to use it. Nothing requires Baz to actually use Foo<Baz>.
The type system in C# simply cannot enforce what you would like enforced. Even with this pattern in place, you are still in the same position as before. You still have to trust the implementers of the derived classes to do it correctly.
For more on this topic, you might read this blog.

Defining factory methods in interfaces or abstract superclasses of the product class

I have an abstract super class and subclasses inheriting from it.
Each subclass MySubclass shall have a public static MySubclass CreateFrom(ISomething something) factory method. The interface of its argument is the same for all subclasses, but the return type must of course always be the type of the respective subclass.
Can I somehow achieve this to have static factory methods following an interface or abstract superclass method definition without creating a separate static factory class for each single subclass?
If the ISomething is always of the same (or at least a common) type, you could make the CreateFrom method of the superclass generic and Invoke the constructor of the inherited class with the parameter. Just make sure all your inherited classes have that constructor (Not sure but I don't think there is a way to 'force' a constructor pattern).
public abstract class SuperClass
{
public static T CreateFrom(ISomething something)
{
return (T)Activator.CreateInstance(typeof(T), something);
}
}
public class InheritedClass : SuperClass
{
public InheritedClass(ISomething something)
{}
}
This way you can create instances by calling
SuperClass.CreateFrom<InheritedClass>(something);
Or you split the creation and initialization:
public abstract class SuperClass
{
protected abstract void Initialize(ISomething something);
public static T CreateFrom(ISomething something) where T : new()
{
T result = new T();
T.Initialize(something);
}
}
public class InheritedClass : SuperClass
{
public InheritedClass()
{}
protected override Initialize(ISomething something)
{}
}
You can´t define static members on interfaces as static members belong to a certain class. However I can´t imagine of a reason to use this. You should ask yourself why you need such a functionality. Does a sub-class really have to instantiate itself or can the same easily be done with another independent (factory-)class?
Just create one simple factory-class with a generic parameter that indicates what to create.
class Factory<T> where T: new()
{
T CreateFrom(ISomething param)
{
return new T();
}
}
Now you can simply call it like this:
var myFactory = new Factory<MyClass>();
myFactory.CreateFrom(mySomething);
I resorted to a different solution in similiar kind of requirement. In my superclass which happened to be an abstract one I required to create an instance of subclass to do something with it so I did the following trick:
public abstract class Element
{
protected virtual void copyFrom(Element other)
{
}
protected abstract Elememt newInstanceOfMyType();
public object clone()
{
var instance= newInstanceOfMyType();
instance.copyFrom(this);
return instance;
}
}
Now all my subclasses inheriting from Element class required to override newInstanceOfMyType method to give away instance of its type and then also override copyFrom method to produce a perfect clone. Now people might argue that why an abstract Clone method cant do the same job? Yes it can. But I required cloned instance of subclass as well as an empty instance(without copying anything from current) so I came up with this architecture.

Reimplementation of inherited interface methods

I did not fully understand using Interfaces, so I have to ask :-)
I use a BaseClass, which implements the IBaseClass interface.These interface only contains one declaration :
public interface IBaseClass
{
void Refresh ();
}
So I have implement a Refresh method in my Baseclass :
public void Refresh ()
{
Console.WriteLine("Refresh");
}
Now I want to use some classes which extends from these Baseclass and implements the IBaseClass interface :
public class ChildClass : BaseClass,IBaseClass
{
}
But cause of the implementation of "Refresh" into my BaseClass I does not have to implement the method again. What should I do, to force the implementation of "Refresh" into all childs of BaseClass as well as all childclasses of childclass.
Thanks kooki
You cannot force derived classes to re-implement the method in the way that you have specified. You have three options:
Do not define refresh in the base class. The interface will force child classes to implement it.
Eschew the interface if its only purpose was to force implementation and declare the base class as abstract as well as refresh, for which you would not give an implementation.
Define refresh in the base class as virtual. This allows overrides but will not force them. This is how ToString() works.
This is all assuming that your base class is larger than a single method. If indeed your code is exactly what you posted then Oded's answer is the best choice.
Simple. Don't supply a base class implementation, and you will have to implement the method in every inheriting class.
One way to achieve that is to make BaseClass abstract:
public abstract BaseClass : IBaseClass
{
public abstract void Refresh();
}
What should I do, to force the implementation of "Refresh" into all childs of BaseClass as well as all childclasses of childclass.
Like this:
interface IBase
{
void Refresh();
}
abstract class BaseClass : IBase
{
public abstract void Refresh();
}
class ChildClass : BaseClass
{
public override void Refresh()
{
// Your code
}
}
You can even omit the interface (my rule of thumb: if an interface gets implemented by exactly one class, dump the interface. Don't cling on to interfacitis. An abstract class quite much represents an interface, see also Interface vs Abstract Class (general OO)).
If you do need an implementation in the base class, build it as such:
(abstract) class BaseClass ( : IBase)
{
public virtual void Refresh()
{
// Your code
}
}
Which you can then call from your derived classes:
public override void Refresh()
{
// Your code
// optionally, to call the base implementation:
base.Refresh();
}
If you want to supply a default implementation, do it in your base class by marking it as virtual, so you can override that implementation in subclasses if you want.
Otherwise mark the method as abstract in your base class, so your subclasses are forced to implement the method themselves.
Lets take a look at this step-by-step.
1: You have an interface which defines your code contract defined like so:
public interface IBase
{
void Refresh();
}
2: You have a base class which implements your interface. (you will notice that the implementation for refresh is virtual. This allows you to override this method in derived classes).
class Base : IBase
{
public virtual void Refresh()
{
//Implementation
}
}
3: You have a super class which derives from Base. (you will notice that the derived class does not need to explicitly implement IBase as it's done at a lower level. I'll show you that you can test the integrity of this).
class Child : Base
{
public override void Refresh()
{
base.Refresh(); //You can call this here if you need to perform the super objects Refresh() before yor own.
//Add your implementation here.
}
}
At this point you might be thinking; "Ok, well then how is Child implementing IBase?". The answer is that it is implemented indirectly through Base, and because Child inherits Base, it also gets the implementation for IBase.
Therefore if you were to write:
IBase instance = new Child();
This is perfectly legal because essentially, Child derives from IBase indirectly.
If you wanted to test this, you can do this in your code:
bool canAssign = typeof(IBase).IsAssignableFrom(typeof(Child));
//canAssign should be true as Child can be assigned from IBase.
May be New Keyword can help u in that;
namespace ConsoleApplication1
{
interface IBase
{
void Referesh();
}
public class Base1 : IBase
{
public void Referesh()
{
Console.WriteLine("Hi");
}
}
public class Class1 : Base1, IBase
{
public new void Referesh()
{
Console.WriteLine("Bye");
}
}
class Program
{
static void Main(string[] args)
{
Class1 obj = new Class1();
obj.Referesh();
Console.ReadKey();
}
}
}

c# generics and inheritance

I'm getting a compilation error on following code:
public abstract class DbHandler<T>
{
public abstract bool Save(T obj);
...
}
and its implementing class:
public class SpaghettiTableDb : DbHandler<SpaghettiTable>
{
public bool Save(SpaghettiTable obj)
{
return false;
}
...
}
The error is :
'SpaghettiTableDb' does not implement inherited abstract member 'SeatPicker.DbHandler<SeatPicker.SpaghettiTable>.Save(SeatPicker.SpaghettiTable)'
But I think it does, so I'm not sure why I'm receiving this error.
(SpaghettiTable is just a class with some properties, nothing more)
Any help?
You need to use the override keyword. Otherwise you're not implementing the abstract base class and just creating a "new" separate method on the subclass.
public override bool Save(SpaghettiTable obj)
{
return false;
}
Think of abstract methods just like virtual methods that you override. The only difference is that you force subclasses to provide an implementation of that method whereas virtual methods provide their own implementation that subclasses can optionally override with their own implementation.
EDIT: Additionally, if you want to make your life easier in Visual Studio, you can right-click (or ctrl+.) on the inheritance declaration and choose "implement abstract class" (or something like that, I don't have VS with me right now) which will automatically create all the overridden methods for you.
public class SpaghettiTableDb : DbHandler<SpaghettiTable> //right-click on "DbHandler"
Alternatively, in the empty code space within your class, you can start typing "override", then the IntelliSense will list all overridable members from the base class and when you pick one it will automatically write a default implementation for you.
EDIT:
Just to extend on what you have in your code, without the override keyword, you are creating a new method that belongs to your subclass and not overriding the base class. When you call that method but from the context of using the base class, it won't call your subclass implementation since it doesn't override the base method.
Consider the following classes. (I'm using virtual instead of abstract just so it compiles and have it simpler)
public class BaseClass
{
public virtual void Print()
{
Console.WriteLine("base print");
}
public virtual void AnotherPrint()
{
Console.WriteLine("base another print");
}
}
public class SubClass : BaseClass
{
public override void Print()
{
Console.WriteLine("sub print");
}
public void AnotherPrint()
{
Console.WriteLine("sub another print");
}
}
Note that SubClass.AnotherPrint does not override BaseClass.AnotherPrint.
And when you use code like:
SubClass mySub = new SubClass();
mySub.Print(); //sub print
mySub.AnotherPrint(); //sub another print
BaseClass myBase = mySub;
myBase.Print(); //sub print
myBase.AnotherPrint(); //base another print
Note that through the code, mySub and myBase both point to the same object, but one is typed as SubClass and the other as BaseClass. When the runtime calls myBase.Print(), it can easily check the inheritance of the classes and see that SubClass has overridden the Print method and calls the SubClass implementation. However, since SubClass.AnotherPrint wasn't explicitly marked with override, the runtime/compiler considers that to be a completely different method with no link to the BaseClass.AnotherPrint method. Thus the runtime sticks with the base class implementation. When your instance is typed as the SubClass though, the compiler does see that you're pointing to that new method and essentially not to the base implementation.
You need to use the override keyword when implementing abstract methods or overriding virtual methods.
public override bool Save(SpaghettiTable obj)
{
return false;
}

Why should an abstract class implement an abstract method of an abstract base class?

In the following example, the class Derived implements the abstract method method from class Main. But I can't think of a reason to fill in the method body in the abstract Derived class' implementation. Surely I should only implement abstract methods within real classes.
So how can I avoid doing it? What else can I do?
abstract class Main
{
public abstract void method();
}
abstract class Derived : Main
{
public override void method()
{
}
}
class RealClass : Derived
{
}
Usually if someone has specified that an abstract class has an abstract method, it's either because that class depends on that method for some of what it does, or it's because it's part of an expected API that it wouldn't make sense for the parent class to implement at this time. In either case, there must be an implementation once you get to a non-abstract implementation of the class.
Note also that if you are implementing an interface, you are required to state how that interface will be implemented, even if you just call the member abstract and pass the responsibility onto the subclass
public interface IPet {string GetNoise(); int CountLegs(); void Walk();}
public abstract class Pet : IPet
{
public string Name {get; set;}
public abstract string GetNoise(); // These must be here
public abstract int CountLegs();
public abstract void Walk();
}
When it comes to implementing the sub-class, you have a few choices depending on the circumstances. If your implementation is itself an abstract class, you shouldn't need to implement the abstract method.
public abstract class Quadruped : Pet
{
public override int CountLegs () { return 4; }
}
If your implementation is non-abstract, but the standard reason for the method in question really doesn't apply in your circumstance, you can do a no-op method (in the case of void methods), or return some dummy value, or even throw a NotImplementedException to indicate that the method should never have been called in the first place.
public class Fish : Pet
{
public override string GetNoise() {return "";} // dummy value: fish don't make noise
public override int CountLegs() {return 0;}
public override void Walk() {} // No-op
// public override void Walk() { throw new NotImplementedException("Fish can't walk"); }
}
Does that answer your question?
If there's no implementation of method in Derived then you can just make Derived abstract as well:
abstract class Derived : Main
{
}
class RealClass : Derived
{
public override void method() { ... }
}
EDIT: To clarify the comments - if there is no meaningful implementation of an abstract method in a subclass, then one does not need to be provided. This will however require that the derived class is itself abstract, and an implementation must be provided somewhere in the chain of descendant classes to some concrete subclass. I am not saying you should leave the implementation of method empty, as it is in the question, but rather you remove the override in Derived and mark the class abstract. This forces RealClass to provide an implementation (or itself be marked abstract).
All non-abstract descendant classes must provide concrete implementations of abstract methods. If you don't provide an implementation, then it's impossible to call that method.
If some concrete classes don't have an obvious proper implementation of a abstract method then your object design is incorrect. Maybe you should have an abstract class with some abstract methods (but not all). That class could have an both an abstract descendant and some concrete descendants.

Categories