Lets say i have the following c# classes:
abstract class a
{
protected abstract void SomeMethod();
}
abstract class b : a
{
protected abstract override void SomeMethod();
}
class c : b
{
protected override void SomeMethod()
{
}
}
Is there actually any point in overriding the method in b when it could just as easily be writen as:
abstract class b : a
{
}
What would be the "prefered" way of writting b? And if there is no point overriding an abstract method or property why is it allowed?
One reason you might want to allow it: it shows intent. It explains that yes, you know this method is abstract in the base class. I know that, and I still want it to be abstract here.
That way, if the base class removes the method, your abstract class will fail to compile, rather than only the concrete class (which may not even be in your code).
That said, it's not a particularly important reason... I'd normally leave it out.
Additional to the already said:
override could also be used to declare attributes that are not defined in the base class. If still not having an implementation, it will be an abstract override.
abstract class b : a
{
[SomeAttribute]
protected abstract override void SomeMethod();
}
I normally don't re-declare abstract methods when I don't actually intend to supply an implementation - for several reasons:
I doesn't change the semantics of your code.
It adds one more thing to refactor if the base class changes.
It leads to inconsistency of new abstract methods are added to the base class and you don't add them to intermediate classes.
It's quite painful to do so in a class hierarchy with more than a few levels.
It clutters your code with declaration that add little value.
Have a look at this blog. Sometimes combining both is useful:
"Good language design usually results
in a few well defined simple
primitives that can be combined
together in intuitive and intelligent
ways. In contrast, poor language
design usually results in many bloated
constructs that don't play well
together.
The "abstract" and "override" keywords
in C# are a great example of this.
They both have simple definitions, but
they can be combined to express a more
complex concept too.
Let's say you have a class hierarchy:
C derives from B, and B derives from
A. A has an abstract method Foo() and
Goo(). Here are 2 scenarios where
"abstract override" would come up. 1)
Let's say B only wants to implement
Goo(), and let C implement Foo(). B
can mark Foo() as "abstract override".
This clearly advertises that B
recognizes Foo() is declared in the
base class A, yet it expects another
derived class to implement it.
2) Let's say B wants to force a C to
reimplement Foo() instead of using A's
definition of Foo(). B marks Foo() as
both override (which means B
recognizes Foo() is declared in the
base class) and abstract (which means
B forces derived class C to provide an
implementation; regardless that A
already provided an implementation).
This came up in one of my recent blog
entries here. In that example,
A=TextReader, Foo=ReadLine, B= a
helper class, C=some class that wants
to implement ReadLine() instead of
Read(). Now TextReader already has a
default implementation of ReadLine()
based on Read(), but we want to go the
other way around. We want an
implementation of Read() based off a
derived classes implementation of
ReadLine(). Thus B provides an
implementation of Read() that consumes
ReadLine(), and then marks ReadLine()
as "abstract override" to force C to
redefine ReadLine() instead of picking
up the one from TextReader.
In summary, "abstract override" is
cool not because it's yet one more
language feature to express some
complex corner case; it's cool because
it's not one more language feature.
The neat part is that you don't really
need to think about any of this. You
just use the individual basic concepts
naturally, and the complicated stuff
comes together automatically."
This is my example code for scenario 1:
public abstract class A
{
public abstract void Foo();
public abstract void Goo();
}
public abstract class B : A
{
public abstract override void Foo();
public override void Goo()
{
Console.WriteLine("Only wanted to implement goo");
}
}
public class C : B
{
public override void Foo()
{
Console.WriteLine("Only wanted to implement foo");
}
}
And my sample code for scenario 2:
public abstract class A
{
public virtual void Foo()
{
Console.WriteLine("A's Foo");
}
public abstract void Goo();
}
public abstract class B : A
{
public abstract override void Foo();
public override void Goo()
{
Console.WriteLine("Only wanted to implement goo");
}
}
public class C : B
{
public override void Foo()
{
Console.WriteLine("Forced to implement foo");
}
}
In your question the code is not that useful, but that doesn't mean that abstract and override combined is not useful.
You should not need to override SomeMethod() in b. An abstract class declares that there can be undefined/abstract methods in it. When you extend one abstract class with another, it implicitly inherits any abstract methods from the parent.
Related
Here's one, I have an abstract class like this...
public abstract class SpaceshipManager
{
...
public abstract void BuildWith(ParseObject po);
// "Or ..."
public abstract void BuildWith(string label);
...
}
The sense is, the derived classes must implement BuildWith a ParseObject, "OR", they can implement BuildWith using a string.
Now, at the moment I just do this ...
public abstract void BuildWith(object data);
Which is fine - but is there a better way?
Another way to look at it, you could have two methods
BuildKeidranType()
BuildBastionType()
The concept is that derived classes have to implement at least one of these.
Is there any such thing in c#?
You could use generics:
public abstract class SpaceshipManager<T>
{
public abstract void BuildWith(T source);
}
public class StringBuilderSpaceshipManager : SpaceshipManager<ParseObject> { ... }
Well there is nothing like that in c#. Generics could have given you a way out.
But seeing that you are deriving from MonoBehavior, i am assuming it's Unity you are working with, where there are constraints like the class name must be same as the file name etc. etc. which don't give too many options for generic behaviors. So avoiding generic classes and focusing on generic methods.
The following is a very crude example using generics just for fun and might not be much better than your current example where you take the parameter as an object. Nevertheless here goes:
public abstract class SpaceshipManager: MonoBehaviour
{
public void BuildWith<T>(T po)
{
if (ValidateBuildParam<T>())
{
Build<T>(po);
}
}
protected abstract bool ValidateBuildParam<T>();
protected abstract void Build<T>(T type);
}
public class DerivedA : SpaceshipManager
{
protected override void Build<T>(T po)
{
//Build here
}
protected override bool ValidateBuildParam<T>()
{
return (typeof(T) != typeof(ParseObject)) ? false : true;
}
}
public class DerivedB : SpaceshipManager
{
protected override void Build<T>(T po)
{
//Build here
}
protected override bool ValidateBuildParam<T>()
{
return (typeof(T) != typeof(string)) ? false : true;
}
}
Now there are some drawbacks like the following usage wont be incorrect:
SpaceshipManager spMan = new DerivedA();
spMan.BuildWith<int>(5);
This will compile and run but would build nothing. So it would be good if you change the return type of BuildWith, return null if Validation fails or a bool true or false
No, there's no such thing.
If the derived class implemented only one of the overloads, how would the caller know which one is implemented?
NO, such things which you are asking is not available in c#. In c# there is interface but you would have to implement all of the methods in derived class because if you would implement one of those caller would get confused.
As others have already told you, you cannot define abstract methods as optional to be implemented somehow.
If possible, I would suggest defining some kind of common type that can serve as input for the BuildWith method. For example, can the label string also be represented as a ParseObject? If not, can you think of some common abstraction for the two?
If the answer to both of these is no, that I would pose that these two methods probably shouldn't be overloads in the first place.
If the answer is yes, then you can make only one of these methods abstract:
public abstract class SpaceshipManager : MonoBehaviour
{
public abstract void BuildWith(ParseObject po);
public void BuildWith(string label)
{
// Static method or constructor here to represent label as a ParseObject.
BuildWith(ParseObject.FromLabel(label))
}
}
In this example, ParseObject is the common abstraction. It could also be another class or interface however.
Depending on the situation, the generics option that #Lee posted could also be a good solution, perhaps combined with a non-generic base type:
abstract class SpaceshipManager<T> : SpaceshipManager
{
public abstract void BuildWith(T source);
}
abstract class SpaceshipManager
{
// Other methods here
}
If neither of these solutions work for you, you could always make the method(s) virtual instead and override the behavior if needed, but it's somewhat doubtful that this design makes sense in your situation.
You can implement two Interfaces. IBuildWithFromString and IBuildWithFromParseObject. Then you can query which Interface is implemented by trying to cast to this Interface and in case of successand you can call the appropriate method.
I have no practical experience with OO design, thus I am hesitant as to the solution I adopted for the following problem:
I have to process network text files that come from N different sources, in different formats - with the processing consisting in the classical reading, computations, and insertion into database.
The solution I devised was to create a class that defines all functionalities/behaviors that are core/file-format-independent, and create derived classes from the latter where each contain the appropriate format-reading logic, according to the file-type the given class handles.
All files are read via File.ReadAllLines(), what differs is mapping fields from the file into the main object's variables. So I did this by defining an event in the base class, that is called after File.ReadAllLines(), and all derived classes attach their mapping logic to the inherited event.
But I understand this solution is not correct design-wise. First of all, there is no meaning in instantiating the base class, so it should be abstract. The reason I did not make it abstract is that the construction code for all the derived objects is the same, so I defined it as the base constructor. Should I declare an "Initialize" method in the abstract class and simply call it in every derived class's constructor? (looks weird...)
Perhaps interfaces? I don't see how using an interface would give me any benefits here, besides it will not solve this "constructor" problem...
What is the correct solution?
Code demonstration of my scenario:
public delegate void myDelegate(object parameter);
class Base
{
#region Attributes
...
#endregion
public Base(object p)
{
//initialization code
...
}
#region Methods
protected void m1() { }
protected void m2() { }
...
#endregion
public event myDelegate myEvent;
}
class Child1
{
public Child1(object o) : base(o)
{
this.myEvent += new myDelegate(ChildMethod);
}
public void ChildMethod(object o)
{
...
}
}
First of all, there is no meaning in instantiating the base class, so it should be abstract. The reason I did not make it abstract is that the construction code for all the derived objects is the same, so I defined it as the base constructor.
You still can make the base class abstract yet have common constructor logic in the base class constructor. I see in your code you've already figured out how to call the base class constructor; that's all you need to do.
abstract class Base {
public Base(object o) { }
public abstract void M();
}
class Derived : Base {
public Derived(object o) : base(o) { }
public override void M() { }
}
Is it possible to override a base class method in C++, like we can do in C# using the override keyword ?
Please Help
Thank You
Yes.
Just make the base method virtual.
C++ doesn't have an override keyword; any method with the same signature (including parameter types and const-ness) as a virtual base method will override it.
Only in C++0x, the next upcoming standard of the C++ language. In C++03, that is the current C++ you override implicitly, that is you don't mark the overriding method explicitly as an overriding one. But be careful, if you accidentally write another signature but the same name, the base class function will be hidden and not overriden!
struct X
{
virtual void f() {...};
};
struct Y:X
{
void f() {...} //overrides X::f
};
struct Z:X
{
void f() const {... } //hides X::f!!!
};
The only thing that can differ in the functions' declarations is that if in base class the function returns T1* ( or T1&) and in derived class T2* (or T2&) and T2 is derived from T1 then it's OK, it's still overrifing, not hiding. HTH
Yes, you can override base class methods; if you use the keyword virtual in your base class, the binding of the method will be dynamic (i.e. fully polymorphic); if you don't use the keyword virtual in your base class, the binding of the method will be static.
A lot of answers have said you make a base class function virtual, this is often done but not needed. you could just do the following...
class A{
public:
void foo();
}
class B: public A{
public:
void foo();
}
class C: public A{
public:
void foo();
}
If you had an array of A pointers such as A* basePTR[2] you can instance basePTR[0] as an instance of B then basePTR[1] as an instance of C. but if you tried to call basePTR[0]->foo() you will call A::foo()
if you defined A as
class A{
public:
virtual void foo();
}
then calling basePTR[0]->foo() will call B::foo()
Their is overhead for using this functionality as at run time a look up has to be done to see if you are calling the base functions foo() or a derived class's foo() but normally, this feature is worth the relatively minor performance hit.
You could define A as
class A{
public:
virtual void foo() =0;
}
the =0 at the end of foo() means that this function is a pure virtual function, this means that it HAS to be defined by a derived class and you can't make an instance of A. A good example of where you would use this would be in a game, you might have a base class GameToken that has an XYZ position and a pure virtual function draw and update. from this you could derive player AI dynamicObject etc... your engine could then just store one array of type GameToken* and iterate through this array calling draw() and update() for all the different types in the array
Is there a construct in Java or C# that forces inheriting classes to call the base implementation? You can call super() or base() but is it possible to have it throw a compile-time error if it isn't called? That would be very convenient..
--edit--
I am mainly curious about overriding methods.
There isn't and shouldn't be anything to do that.
The closest thing I can think of off hand if something like having this in the base class:
public virtual void BeforeFoo(){}
public void Foo()
{
this.BeforeFoo();
//do some stuff
this.AfterFoo();
}
public virtual void AfterFoo(){}
And allow the inheriting class override BeforeFoo and/or AfterFoo
Not in Java. It might be possible in C#, but someone else will have to speak to that.
If I understand correctly you want this:
class A {
public void foo() {
// Do superclass stuff
}
}
class B extends A {
public void foo() {
super.foo();
// Do subclass stuff
}
}
What you can do in Java to enforce usage of the superclass foo is something like:
class A {
public final void foo() {
// Do stuff
...
// Then delegate to subclass
fooImpl();
}
protected abstract void fooImpl();
}
class B extends A {
protected void fooImpl() {
// Do subclass stuff
}
}
It's ugly, but it achieves what you want. Otherwise you'll just have to be careful to make sure you call the superclass method.
Maybe you could tinker with your design to fix the problem, rather than using a technical solution. It might not be possible but is probably worth thinking about.
EDIT: Maybe I misunderstood the question. Are you talking about only constructors or methods in general? I assumed methods in general.
The following example throws an InvalidOperationException when the base functionality is not inherited when overriding a method.
This might be useful for scenarios where the method is invoked by some internal API.
i.e. where Foo() is not designed to be invoked directly:
public abstract class ExampleBase {
private bool _baseInvoked;
internal protected virtual void Foo() {
_baseInvoked = true;
// IMPORTANT: This must always be executed!
}
internal void InvokeFoo() {
Foo();
if (!_baseInvoked)
throw new InvalidOperationException("Custom classes must invoke `base.Foo()` when method is overridden.");
}
}
Works:
public class ExampleA : ExampleBase {
protected override void Foo() {
base.Foo();
}
}
Yells:
public class ExampleB : ExampleBase {
protected override void Foo() {
}
}
I use the following technique. Notice that the Hello() method is protected, so it can't be called from outside...
public abstract class Animal
{
protected abstract void Hello();
public void SayHello()
{
//Do some mandatory thing
Console.WriteLine("something mandatory");
Hello();
Console.WriteLine();
}
}
public class Dog : Animal
{
protected override void Hello()
{
Console.WriteLine("woof");
}
}
public class Cat : Animal
{
protected override void Hello()
{
Console.WriteLine("meow");
}
}
Example usage:
static void Main(string[] args)
{
var animals = new List<Animal>()
{
new Cat(),
new Dog(),
new Dog(),
new Dog()
};
animals.ForEach(animal => animal.SayHello());
Console.ReadKey();
}
Which produces:
You may want to look at this (call super antipatern) http://en.wikipedia.org/wiki/Call_super
If I understand correctly you want to enforce that your base class behaviour is not overriden, but still be able to extend it, then I'd use the template method design pattern and in C# don't include the virtual keyword in the method definition.
No. It is not possible. If you have to have a function that does some pre or post action do something like this:
internal class Class1
{
internal virtual void SomeFunc()
{
// no guarantee this code will run
}
internal void MakeSureICanDoSomething()
{
// do pre stuff I have to do
ThisCodeMayNotRun();
// do post stuff I have to do
}
internal virtual void ThisCodeMayNotRun()
{
// this code may or may not run depending on
// the derived class
}
}
I didn't read ALL the replies here; however, I was considering the same question. After reviewing what I REALLY wanted to do, it seemed to me that if I want to FORCE the call to the base method that I should not have declared the base method virtual (override-able) in the first place.
Don't force a base call. Make the parent method do what you want, while calling an overridable (eg: abstract) protected method in its body.
Don't think there's any feasible solution built-in. I'm sure there's separate code analysis tools that can do that, though.
EDIT Misread construct as constructor. Leaving up as CW since it fits a very limited subset of the problem.
In C# you can force this behavior by defining a single constructor having at least one parameter in the base type. This removes the default constructor and forces derived types to explcitly call the specified base or they get a compilation error.
class Parent {
protected Parent(int id) {
}
}
class Child : Parent {
// Does not compile
public Child() {}
// Also does not compile
public Child(int id) { }
// Compiles
public Child() :base(42) {}
}
In java, the compiler can only enforce this in the case of Constructors.
A constructor must be called all the way up the inheritance chain .. ie if Dog extends Animal extends Thing, the constructor for Dog must call a constructor for Animal must call a constructor for Thing.
This is not the case for regular methods, where the programmer must explicitly call a super implementation if necessary.
The only way to enforce some base implementation code to be run is to split override-able code into a separate method call:
public class Super
{
public final void doIt()
{
// cannot be overridden
doItSub();
}
protected void doItSub()
{
// override this
}
}
public class Sub extends Super
{
protected void doItSub()
{
// override logic
}
}
I stumbled on to this post and didn't necessarily like any particular answer, so I figured I would provide my own ...
There is no way in C# to enforce that the base method is called. Therefore coding as such is considered an anti-pattern since a follow-up developer may not realize they must call the base method else the class will be in an incomplete or bad state.
However, I have found circumstances where this type of functionality is required and can be fulfilled accordingly. Usually the derived class needs a resource of the base class. In order to get the resource, which normally might be exposed via a property, it is instead exposed via a method. The derived class has no choice but to call the method to get the resource, therefore ensuring that the base class method is executed.
The next logical question one might ask is why not put it in the constructor instead? The reason is that it may be an order of operations issue. At the time the class is constructed, there may be some inputs still missing.
Does this get away from the question? Yes and no. Yes, it does force the derived class to call a particular base class method. No, it does not do this with the override keyword. Could this be helpful to an individual looking for an answer to this post, maybe.
I'm not preaching this as gospel, and if individuals see a downside to this approach, I would love to hear about it.
On the Android platform there is a Java annotation called 'CallSuper' that enforces the calling of the base method at compile time (although this check is quite basic). Probably the same type of mechanism can be easily implemented in Java in the same exact way. https://developer.android.com/reference/androidx/annotation/CallSuper
Suppose I have the following class hierarchy:
Class A {...}
Class B : A {...}
Class C : A {...}
What I currently have is
Class D<T> where T : A {...}
but I'd like something of the form
Class D<T> where T in {B,C}
This is due to some odd behavior I'm not responsible for where B and C have common methods which aren't in A, but it would be nice to be able to call them in D on T.
Note: I don't have access to A,B or C to edit them
You need to define an interface for the common methods that are in B and C (lets call it Ibc), make B and C implement this interface, and then you can write:
Class D<T> where T : A, Ibc {...}
This isn't directly possible.
As others suggest, you could define an interface and implement it in both B and C.
If this isn't an option (e.g., if these classes are beyond your control), what I might suggest is this: first, start with an abstract class that includes all the functionality you can achieve with any T deriving from A. Then say you have some methods that exist for both B and C that aren't a part of A. In D you can make these abstract methods to be implemented by subclasses:
public abstract class D<T> where T : A
{
protected T _member;
public void DoSomethingAllTsCanDo()
{
_member.DoSomething();
}
public abstract void DoSomethingOnlyBAndCCanDo();
}
Then you can inherit from the base class for each type B and C and override the abstract method(s) to provide the appropriate functionality:
public class DB : D<B>
{
public override void DoSomethingOnlyBAndCCanDo()
{
_member.DoSomethingOnlyBCanDo();
}
}
public class DC : D<C>
{
public override void DoSomethingOnlyBAndCCanDo()
{
_member.DoSomethingOnlyCCanDo();
}
}
First, If B and C have common methods, it is a design flaw they don't share an interface. That said, you can fix that even without having access to B and C.
It is possible to create a common interface. Suppose you have:
public class A
{
}
public class B : A
{
public void Start() { }
}
public class C : A
{
public void Start() { }
}
You can create a common interface:
public interface IStartable
{
void Start();
}
And use it on derived classes from B and C:
public class BetterB : B, IStartable
{
}
public class BetterC : C, IStartable
{
}
You may not be able to achieve that if you get B and C instances as is, but it can be considered if you create them. In fact, with specialized classes of B and C, you may use the interface instead of D<T>.
Do B and C implement the same interface? That may be a better route.
Some options:
Make an interface IderivedFromA that contain the common methods from B and C.
Looks like this is impossible from your question
In D cast T to dynamic and call the methods dynamically
The most easy solution, if you can use .Net 4
In D test if the you deal with an B or C, cast, and call
Will be checked by the compiler, and is possible from .Net 2
The Dan Tao answer: Create a specific implementation of D<T> for B and C, these can call the methods from B and C directly. (Didn't think of this one myself).
Will only work if the "user-source" knows it is dealing with B or C, and does not use the abstract A to use D<A>. Instead it should use DB or DC. But I think this is the case, otherwise you didn't need generics.
The where constrain in C# does not allow you to specify multiple classes as a choice.
Also if you will specify multiple where contains, then they both has to be satisfied. There is no OR logic for constrain.
Here is specification: http://msdn.microsoft.com/en-us/library/bb384067.aspx
Answers from Grzenio seems right for you. Extract common behavior into the common interface for B and C. Then you can use that interface as a constrain.
Since you don't have access to the source, the only real answer (unless you are willing to lose safety by using dynamic) is explicitly check for B/C and cast.