Reimplementation of inherited interface methods - c#

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();
}
}
}

Related

How to force overrides in a derived class from non abstract base classes?

Is there any way for a derived class to be forced to override it's base classes' virtual method ?
The base class can't be abstract in my case so i can't use an abstract method. So i am wondering if this is even possible in C# ?
This is the general setup i am trying to do:
public abstract SomeAbstractClass {
//Test() does not belong here.
}
public ClassA : SomeAbstractClass{
protected virtual void Test(){};
}
public ClassB : ClassA{
// how can i make this mandatory in the same way abstract methods work
protected override void Test(){};
}
Is it possible at all ?
Is another intermediary class an acceptable solution? If so, you can override the virtual method as an abstract one, which would force inheritors to override.
The end result would look something like this:
public abstract class SomeAbstractClass { }
public class ClassA : SomeAbstractClass {
protected virtual void Test() { }
}
public abstract class ClassB : ClassA {
protected override abstract void Test();
}
public class ClassC : ClassB {
protected override void Test() { }
}
ClassC is forced to implement Test to inherit from ClassB, as Test is now abstract at this level of inheritence.
Is there any particular reason you couldn't use an Interface? This sounds like a good place for one since it doesn't define an implementation and therefore requires any class that implements the interface to define the method details.
I try to use composition over inheritance unless there is a very good reason to have an inheritance hierarchy.
// Whatever your top level abstract class is
public abstract class SomeAbstarctClass
{
}
// Interface that defines the signature of the Test method, but has no implementation detail.
// No need to define it as virtual here, since there is no implementation
public interface ITestMethodInterface
{
void Test();
}
// Inherit from the absract class and implement the interface. This forces the new class to implement the interface, and therefore the Test method
public class ClassA : SomeAbstarctClass, ITestMethodInterface
{
// This CAN, if needed be virtual, but I would recommend if it isn't absolutely needed for a hierarchy to simply implement it here and use the Interface in ClassB
// to force the derviced class to implement it instead.
public void Test()
{
// Class A's implementation of Test()
}
}
// Here's where it might get complicated, if you MUST have a hierachy where Class B MUST inherit from Class A instead of SomeAbstractClass, then the implementation will carry over
// and it becomes difficult to FORCE the derviced class to override from ClassA
public class ClassB : SomeAbstarctClass, ITestMethodInterface
{
public void Test()
{
// Class B's implementation of Test()
}
}

How to have an abstract class require an interface to be implemented by descendant classes?

I want to make an abstract class that imposes a restriction that its child classes must implement an interface. I want to avoid having to implement the interface class in the abstract class. The code below won't do what I'd like. Does anyone have a suggestion of what I could do?
public interface IItem()
{
bool IsUsable();
}
public abstract class Item : IItem
{
MemberVar var;
public void DoSomething()
{
//Do something
}
}
public class Something : Item
{
public bool IsUsable()
{
return true;
}
}
Just make the method abstract in your abstract class :
public abstract class Item : IItem
{
//...
public abstract bool IsUsable();
}
In the classes that inherit the Item class use the override keyword :
public override bool IsUsable()
{
// Do stuff
}
The overriding implementations stubs can be automatically added by VS by right-clicking on the parent abstract class and selecting Implement Abstract Class :
implement the interface in the base class with abstract methods and/or properties
Simply add abstract keyword to every method/properties that the interface requires to implement.
For instance, this is how the DoSomething() method should look:
public abstract void DoSomething();
This way the derived classes will have to implement the interface themselves.

Child use of interface

I have a user control that will handle images on a form. But depending on what the source is (web cam or ID scan or other video source) the user control is different.
But they share some common features so I want to create a base class.
My other controls all have some interface items that I need. I would like to declare the interface at the base level though and just implement at the class level. But virtual and override seems to be the closest way to get what I want. Is there any to do it, force the new class to implement the interface assigned at the base class? Looking around it look like making the class abstract (which I don't fully understand) might be a start. If it was just methods that might be alright, but I am also using properties. In that area I have hit a dead end in my searches for answers. Here is what I have so far. Am I on the right track? I just have not worked with abstract classes at all and only limited exposure to interfaces. From the research I think I have the method correct just not sure about the property.
public interface RequiredAnswer
{
void LabelRequiredFieldEmpty();
bool AnswerRequired{ get;}
}
public abstract partial class ExtImage : UserControl, RequiredAnswer
{
public virtual bool AnswerRequired
{
get
{
throw new NotImplementedException ("Answer Required");
}
}
public abstract void LabelRequiredFieldEmpty ()
{
//checkBox_AgreementAcceptedText.ForeColor = Color.Red;
}
So I would have a class
public partial class ExtImageWebCam : ExtImage
{
public override bool AnswerRequired
{
get
{
return valueFromThisClassThatMeansAnAnswerIsRequired;
}
}
public override void LabelRequiredFieldEmpty ()
{
// do something
}
}
When you declare a method abstract, you are basically saying that a child class must supply the definition of the method. You can make properties abstract. This sounds like it is exactly what you need.
Here is the MSDN article for further reference.
From MSDN
Properties
Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax.
It is an error to use the abstract modifier on a static property.
An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
Continuing later
In this example, the class DerivedClass is derived from an abstract class BaseClass. The abstract class contains an abstract method, AbstractMethod, and two abstract properties, X and Y.
abstract class BaseClass // Abstract class
{
protected int _x = 100;
protected int _y = 150;
public abstract void AbstractMethod(); // Abstract method
public abstract int X { get; }
public abstract int Y { get; }
}
Abstract base class with an Interface
An abstract class must provide implementation for all interface members.
An abstract class that implements an interface might map the interface methods onto abstract methods. For example:
interface I
{
void M();
}
abstract class C : I
{
public abstract void M();
}
First of all, interfaces should start with an I by convention, so your interface would be IRequiredAnswer.
Second, if you want to force the inherited classes to implement their own methods rather than inheriting them, just make them abstract in the base class:
public abstract class ExtImage : UserControl, IRequiredAnswer
{
public abstract bool AnswerRequired { get; }
public abstract void LabelRequiredFieldEmpty ();
}
Your child classes would then have to implement the method and property.
You're on the right track. Here's a simple example of what you could do. Making the Bar() method abstract forces the inheritors to implement it.
public interface IFoo{
void Bar();
}
public abstract class BaseFoo : IFoo
{
public abstract void Bar();
public void Implemented(){
Debug.WriteLine("this is a shared implementation");
}
}
public class KungFoo : BaseFoo{
public override void Bar()
{
}
}
You are on the right track for the creation of an interface and then defining an abstract class for your purpose.
Standard naming conventions for an interface has been broken however, interfaces are usually prefixed with an I to help identify them
public interface IRequiresAnswer
{
void LabelRequiredFieldEmpty();
bool AnswerRequired { get; }
}
I would also suggest changing the AnswerRequired property to a function as your concrete class says "do somthing to find result". Properties are usually meant to be quick, so performing any calculation within a property is masking that real work takes place when you call the property. With a function it is more apparent to callers that the result will not be achieved immediately.

C#: Can a Child class restrict access to Parent class methods?

I have a need for two slightly different classes, that have the same members, but one of the classes needs to have less interaction possibilities by the user. I am hoping to inherit the second class from the first.
Is there a way to restrict access to parent methods from the child class, so that if somebody creates a child object, they will not be able to access certain parent class methods (which are public in the parent class)?
No, and here's why:
class Animal {
public void Speak() { Console.WriteLine("..."); }
}
class Dog : Animal {
remove void Speak(); // pretend you can do this
}
Animal a = GetAnAnimal(); // who knows what this does
a.Speak(); // It's not known at compile time whether this is a Dog or not
You should have a base abstract class to hold the things in common of both classes, and then let the other two classes inherit from it and add methods and properties, etc.
abstract class MyBaseClass
{
public int SharedProperty { get; set; }
public void SharedMethod()
{
}
}
class MyClass1 : MyBaseClass
{
public void Method1()
{
}
}
class MyClass2 : MyBaseClass
{
public void Method2()
{
}
}
MyClass1 has: SharedProperty, SharedMethod, and Method1.
MyClass2 has: SharedProperty, SharedMethod, and Method2.
Not exactly, no. The closest you could come would be to provide virtual methods in the base (parent) class and override/new those in the derived (child) class, and provide no behaviour, or exceptions as appropriate;
public class Base
{
public virtual void DoSomething()
{ . . . }
}
public class Derived : Base
{
public override void DoSomething()
{
throw new NotSupportedException("Method not valid for Derived");
}
}
Create the base class, and make the methods that should be hidden protected.
Create an interface that declares the methods you want public
Create a child class, inherited from the base class, and explicitly implement the interface. Call the protected methods from the interface implementation methods.
Then a user of the child class can only see members of the interface (this requires them to cast the instance as the interface)

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