1) OnCreate is public method of instantiated object from ClsLast class. But I wanted to restrict OnCreate method as protected.
interface InterFace {
void OnCreate();
}
class ClsFirst implements InterFace {
#Override
public void OnCreate() { }
}
class ClsLast extends ClsFirst{ }
class Test {
static void main(){
ClsLast objClsAct = new ClsLast();
objClsAct.OnCreate();
}
}
2) If I set OnCreate method as protected in InterFace
interface InterFace {
protected void OnCreate();
}
I'm getting error like this:
Illegal modifier for the interface method OnCreate; only public & abstract are permitted
3) If I set protected the method inside the ClsFirst class which implements InterFace like this:
interface InterFace {
void OnCreate();
}
class ClsFirst implements InterFace {
#Override
protected void OnCreate() { }
}
I'm getting this error:
Cannot reduce the visibility of the inherited method from InterFace
4) When I change the ClsFirst as abstract class and implements InterFace
interface InterFace {
void OnCreate();
}
abstract class ClsFirst implements InterFace {
}
I haven't to implement OnCreate method inside the ClsFirst class but ClsLast why?
Summary
How can I set Interface methods can only be used in derived classes?
Why can't I set methods with protected access inside Interface?
Why can't I set the accessor type of Class different than public after I implement the InterFace?
abstract classes that even if they implements an interface don't have to add unimplemented methods itself until one class derives abstracted classes. Why?
Thank you so much for your kind answers from now.
An interfaceis per definition a public contract. By implementing an interface you promise to provide a set of methods (and properties in other languages).
An interface has nothing in common with abstract classes because you can implement as many interfaces as you want on a single class and you implement instead of derive from it.
An abstract class is a base class, its like a partially functionally base which is used to share implementation details between different classes and provides a contract, too. However it's more an internal contract for all derived classes. Most times abstract classes are used to force all derived classes into a common pattern instead of sharing a public contract.
An abstract class can force a derived class to implement a method (or provide a suitable default implementation using the virtual keyword) and take use of this method (this is called Template Pattern).
If you implement an interface on an abstract class you don't have to provide all interface methods because the abstract class can not be instantiated. However if you don't implement all interface methods the first non abstract class in your hierarchy has to provide the missing methods.
Interface methods are always public. You can not reduce the scope of these methods. Use a protected abstract method instead in an abstract class.
You cannot do it. You can set methods both as virtual or abstract if you have an middle class which implements only a part of defined in interface contract.
You also cannot do it and the reason is simple, interface defines a contract, a set of operations which implementation is requested to have. You can implement the interface explicitly in your abstract class or restrict whole interface to be "internal", at least in c# in case if you would like to keep it 'in-house'.
You cannot do it because you promised to implement an interface.
Because another thing which you indirectly pointed once you mark class as an abstract is that you cannot instantiate it. Therefore you pass the requirement of implementing interface to the first class which you can create the instance of (I mean the chain of inheritance).
ad1. (c# example1)
interface IDummyInterface
{
void OnCreate();
void Process();
void OnFinish();
}
abstract class DummyAbstract : IDummyInterface
{
public virtual void OnCreate()
{
}
public abstract void Process();
public void OnFinish()
{
OnFinishInternal();
}
protected abstract void OnFinishInternal();
}
class DummyImplementor : DummyAbstract
{
public override void OnCreate()
{
// some other action here
base.OnCreate();
}
public override void Process()
{
}
protected override void OnFinishInternal()
{
}
}
Actually you can hide the method, until the your concrete class is casted to an "Interface" instance by implementing the Interface explicitly:
abstract class ClsFirst : Interface
{
void Interface.OnCreate()
{
this.OnCreate();
}
protected abstract void OnCreate();
}
ClsFirst last = new ClsLast();
last.OnCreate(); // Compiler Error, since OnCreate() is protected
Interface lastAsInterface = last;
lastAsInterface.OnCreate(); // Works, and calls the abstract OnCreate() method.
1) Why would you want to implement a protected interface to begin with? It does not add any value. You already have a way to make sure all derived classes comply with a given contract:
protected abstract void OnCreate();
2) Interfaces define a public contract. By public I mean that it has the same accesibility as the interface itselft. That is why accesibility modifiers are not permitted when defining interface members.
3) You can not decrease accesibility of any virtual member or interface members as you would be breaking the interface's contract. In your example ((IOnCreate)ClsFirst).OnCreate() would not be possible as OnCreate() is not accesible, which would mean that ClsFirst does not implement IOnCreate interface.
Related
Can anyone explain to me why this works the way it does. The output comes out to "Print This". But how does the base class call bar(), when there is no implementation.
abstract class Base
{
protected virtual void foo()
{
bar();
}
protected abstract void bar();
}
class Sub : Program
{
protected override void foo()
{
base.foo();
}
protected override void bar()
{
Console.WriteLine("Print This");
}
static void Main(string[] args)
{
Sub obj = new Sub();
obj.foo();
}
}
That's the whole point of an abstract class: that it will only ever exist concretely as an instance of the derived class(es). By declaring abstract methods or properties, it is simply forcing the derived class(es) to provide concrete implementations of those members. In this way, if you have an instance of type Base, you can call myInstance.bar and you know that the derived class has implemented it because it wouldn't compile otherwise.
By the way, use pascal case when naming methods, i.e. Foo and Bar.
But how does the base class call bar(), when there is no
implementation.
TL;DR answer: because of polymorphism.
If you got this question, how do you explain this?
public interface IStuffMaker
{
void MakeIt();
}
public class StuffMaker : IStuffMaker
{
public void MakeIt()
{
Console.WriteLine("yeah!");
}
}
IStuffMaker maker = new StuffMaker();
maker.MakeIt();
Why if maker is IStuffMaker can call MakeIt()? Because StuffMaker has implemented the so-called method.
In your particular case the reason behind being able to call your abstract method is because an abstract member is polymorphic and a derived class must override it to provide an implementation (same as interface members: they must be implemented).
Abstract classes are a mix of possible concrete members (with body) and abstract ones, which are just member signatures like interface members, but, in opposite to interfaces, since abstract classes can own concrete members, these can call abstract ones because they will be implemented in a derived class.
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();
}
}
}
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.
I get compile errors with this overcomplicated class hierarchy. I wonder if it has anything to do with trying to do DeepCopy() with generics mixed in.
public interface IInterface<T>
{
IInterface<T> DeepCopy();
}
public abstract class AbstractClass<T> : IInterface<T>
{
public abstract IInterface<T> DeepCopy(); // Compiler requires me to declare this public
}
// Everything good at this point. There be monsters below
public class ConcreteClass: AbstractClass<SomeOtherClass>
{
ConcreteClass IInterface<SomeOtherClass>.DeepCopy()
{
return new ConcreteClass;
}
}
I get the following compiler errors:
'IInterface<...>.DeepCopy()': containing type does not implement interface 'IInterface<SomeOtherClass>'
Return bool
Change ConcreteClass IInterface<SomeOtherClass>.MyMethod()
to bool IInterface<SomeOtherClass>.MyMethod()
Edit:
And then you can not use an explicit implementation of the interface, since that does not fulfill the contract of the abstract class you need to implement it like this.
public override IInterface<SomeOtherClass> DeepCopy()
{
return new ConcreteClass();
}
The errors are because the return type of DeepCopy() do not match the declaration in the interface.
Besides that you have a different problem. The abstract class already implements the method from the interface, but in the concrete class you do not implement the abstract method. Instead of the implementation you now have, you should have the following implementation:
public override IInterface<SomeOtherClass> DeepCopy()
{
}
This will implement the abstract method in the abstract class which automatically implements the method in the interface. The reason you need to implement the abstract method in the abstract class, is because that class needs to implement the interface. That is a requirement of a 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.