Questions about Abstract method and interface method [duplicate] - c#

This question already has answers here:
Interfaces vs. abstract classes [duplicate]
(4 answers)
Closed 9 years ago.
Hi all i have some doubts about abstract class and interface
Am not asking about difference between interface and abstract class . Am just asking about different between abstract method and interface method
Abstract methods are same as interface methods . I know if we inherit the interface and abstract class in child class ,then we must implement the those side methods .But we can't implement the non abstract methods. So
my question is what is the different between abstract method and interface ?
and
2". another question is we can partially implement the Non-abstract methods in abstract class , Is it possible to partially implement the abstract method in abstract class ?
I also referred many sites , but does not one give the solution for second question
Question with code
Here is my abstract class and have one abstract method(xxx) and another one non abstract moethod(yyy) and interface method (xxx)
public abstract class AbstractRam
{
public abstract int xxx();// What is the difference in interface method ?
public int yyy()
{
return 2;
}
}
public interface InterfaceRam
{
int xxx();// What is the difference in abstract method ?
}
and i inherited the both in another class
public class OrdinaryClass : AbstractRam
{
public OrdinaryClass()
{
//
// TODO: Add constructor logic here
//
}
public override int xxx()
{
return 1;
}
}
public class OrdinaryClass2 : InterfaceRam
{
public OrdinaryClass2()
{
//
// TODO: Add constructor logic here
//
}
public int xxx()
{
return 1;
}
}
Let see my xxx method , Both methodes are working same , Not a big difference
question : Is it have any difference ? if is it same , then which one is the best way ?

Interface methods are abstract methods. Yes they are the same as abstract methods in abstract classes as both are abstract. A caveat here though is how they are handled when polymorphism comes into play. This can be illustrated with the following code:
interface IA
{
int xxx();
}
abstract class B
{
public abstract int yyy();
}
class C : B, IA
{
public int xxx()
{
return 1;
}
public int yyy()
{
return 1;
}
}
The yyy definition actually hides the abstract method in B and needs to be declared as public override int yyy()... to prevent this.
No. you cannot "partially implement the non-abstract methods in abstract class". You can partially implement an abstract class by providing some concrete methods and some abstract methods. You cannot "partially implement" an abstract method though. A method in an abstract class is either abstract or it isn't.
In your code example, OrdinaryClass is providing an implementation of xxx. OrdinaryClass2 is hiding that abstract method though and providing its own xxx. as mentioned in (1). Please read up on method hiding in C# for more details, eg http://www.akadia.com/services/dotnet_polymorphism.html and Overriding vs method hiding.

Finally I found the answer by my self .
The big difference of abstract method and interface method is
We can implement the abstract method in inside of the same abstract class , but we can't implement the interface method in inside of the same interface .

Related

What is the difference between Pure Abstract Class and Interface in C#? [duplicate]

This question already has answers here:
What's the difference between an abstract class and an interface? [duplicate]
(5 answers)
Closed 3 years ago.
public abstract class PureAbstract
{
public abstract bool GetData();
}
public class ChildClass : PureAbstract
{
public override bool GetData()
{
Console.WriteLine("Pure Abstract Class called");
Console.ReadKey();
return true;
}
}
public class DIClass
{
private PureAbstract pureAbstract;
public DIClass(PureAbstract abstractClass)
{
this.pureAbstract = abstractClass;
this.pureAbstract.GetData();
}
}
class Program
{
static void Main(string[] args)
{
ChildClass child = new ChildClass();
DIClass pureAbstract = new DIClass(child);
}
}
We all know that Interface allows us Multiple Inheritance in C#, but I want to know that if we ignore this reason and assume we always need single inheritance in our application then what is difference between Pure Abstract Class and Interface.
In short, there is no reason why you would want a pure abstract class. Don't ever use pure abstract classes, there is no point in using them. If you want to use a 'pure abstract class', go with interface so you can still use multiple interfaces.
An interface is like a contract. If a class implements an interface it has to implement all the services listed in the interface.
An abstract class is like a skeleton. It defines a certain way its extended classes will work while letting the abstract methods to be unique.

Interface vs Class method parameter ambiguity

I am certain that I simply do not know the name for what I am trying to do, otherwise my googling would be more successful. I currently only find results pertaining to interfaces with same named methods.
I have a few classes that inherit from a common base class and some implement an interface. I have methods accepting the base class or the interface as a parameter. I cannot compile since this causes ambiguity with the error
the call is ambiguous between the following methods or properties: DoThings(IQueryable<A>) and DoThings(IQueryable<B>)` on the call in ConcreteExecutionClass.
Furthermore, generics won't work because type constraints on generics do not make a unique method signature.
Is there a way (or an acceptable pattern) to force the execution to a specific method based on parameter types?
public abstract class A {
// some properties
}
public class ConcreteA : A {
// full implementation
}
public interface B {
// a property
}
public class ConcreteAB : A, B {
// full implementation
}
public abstract class ExecutionClass {
public IQueryable<A> DoThings(IQueryable<A> content){
return A.method().AsQueryable();
}
public IQueryable<B> DoThings(IQueryable<B> content){
return B.interfaceRequiredMethod().method().AsQueryable();
}
}
public class ConcreteExecutionClass : ExecutionClass {
public void Program(){
var objectList = new List<ConcreteAB>{/*....*/};
DoThings(objectList);
}
}
Each of the concrete classes has a class managing linq queries on lists of objects, which each call DoThings(). The goal is to keep the actual implementation of DoThings() transparent to the concrete classes.
I have attempted covariance in the interface, however have been unable to avoid inheriting A which forces down the first code path.
The code above is a simplification of the actual implementation. There are about 10 classes deriving solely from A and 4 deriving from A and B.
I simply created an abstract hierarchy where abstract A is the base and there are 2 abstract classes inheriting from it.

overriding abstract methods in an inherited abstract class

Okay so basically I have the following problem: I'm trying to have an abstract class inherit another abstract class that has an abstract method, but I don't want to implement the abstract method in either of them because a third class inherits from both of them:
public abstract class Command
{
public abstract object execute();
}
public abstract class Binary : Command
{
public abstract object execute(); //the issue is here
}
public class Multiply : Binary
{
public override object execute()
{
//do stuff
}
}
I'm trying to separate binary commands from unary commands but don't want to/can't implement the execute method in either. I thought about having Binary override the abstract method (since it has to), and then just throw a not implemented exception thing. If I make it override, then I must declare a body, but if I make it abstract, then I'm "hiding" the inherited method.
Any thoughts?
You don't need to declare execute() in the Binary class since it's already inherited from Command. Abstract methods don't need to be implemented by other abstract classes - the requirement is passed on to the eventual concrete classes.
public abstract class Command
{
public abstract object execute();
}
public abstract class Binary : Command
{
//the execute object is inherited from the command class.
}
public class Multiply : Binary
{
public override object execute()
{
//do stuff
}
}
Just omit the declaration of execute() in Binary at all. Since Binary is abstract as well, you don't have to implement any abstract methods of its ancestors.

Multiple inheritance with Abstract class and Interface

I have written the following code in C#.NET
public interface IWork
{
void func();
}
public abstract class WorkClass
{
public void func()
{
Console.WriteLine("Calling Abstract Class Function");
}
}
public class MyClass:WorkClass,IWork
{
}
On compiling, I didn't get any error. Compiler is not forcing me to implement the method "func();" in "MyClass", which has been derived from the interface "IWork".Latter, I can gracefully create a instance of the class "MyClass" and call the function "func()". Why the compiler is not forcing me to implement the "func()" method in the "MyClass"(which has been derived from "IWork" interface? Is it a flaw in C#?
While reading about this subject, I found I couldn't easily put it all together in my head, so I wrote the following piece of code, which acts as a cheat-sheet for how C# works. Hope it helps someone.
public interface IMyInterface
{
void FunctionA();
void FunctionB();
void FunctionC();
}
public abstract class MyAbstractClass : IMyInterface
{
public void FunctionA()
{
Console.WriteLine( "FunctionA() implemented in abstract class. Cannot be overridden in concrete class." );
}
public virtual void FunctionB()
{
Console.WriteLine( "FunctionB() implemented in abstract class. Can be overridden in concrete class." );
}
public abstract void FunctionC();
}
public class MyConcreteClass : MyAbstractClass, IMyInterface
{
public override void FunctionB()
{
base.FunctionB();
Console.WriteLine( "FunctionB() implemented in abstract class but optionally overridden in concrete class." );
}
public override void FunctionC()
{
Console.WriteLine( "FunctionC() must be implemented in concrete class because abstract class provides no implementation." );
}
}
class Program
{
static void Main( string[] args )
{
IMyInterface foo = new MyConcreteClass();
foo.FunctionA();
foo.FunctionB();
foo.FunctionC();
Console.ReadKey();
}
}
Gives the following output:
FunctionA() implemented in abstract class. Cannot be overridden in concrete class.
FunctionB() implemented in abstract class. Can be overridden in concrete class.
FunctionB() implemented in abstract class but optionally overridden in concrete class.
FunctionC() must be implemented in concrete class because abstract class provides no implementation.
To better understand the concept behind interfaces, I just give you the correct code of your implementation:
public interface IWork{
void func();
}
public abstract class WorkClass,IWork{
public void func(){
Console.WriteLine("Calling Abstract Class Function");
}
}
public class MyClass:WorkClass{
...
}
The basic rule: You need to include the interface always where the implementation is. So if you create a method within an abstract classes and define an interface of this method, you'll need to implement the interface into your abstract class and then all subclasses will automatically implement this interface.
As a matter of fact, interfaces have 2 kind of functions you can use them for:
1) As a "real" interface providing a generic handling of any class implementing the interface, so you can handle several kind of classes just by one interface (without knowing their real class names). While "handling" means: Calling a method.
2) As a help for other (framework) programmers not to mess up with your code. If you want to be sure that an method won't be replaced with another name, you define an interface for your class containing all "must have" method names. Even if the method is called nowhere, your programmer will get an compile error message when he changed the method name.
Now you can easily handle your Myclass just by the interface IWork.
Because the abstract class implements the interface.
If your class MyClass would not inherit from WorkClass you would get an error saying 'MyClass' does not implement interface member 'IWork.func()'.
But you also inherit from WorkClass, which actually implements the methods that the interface requires.
You can mark func() as abstract if you want to force the classes that inherits from it to implement it like this:
public abstract class WorkClass
{
public abstract void func();
}
I tried with the classes above in my solution.
It inherits the abstract class so the derived class have the func() method definition. This is the reason it was not able to show compiled errors.
func() is not marked as abstract in the WorkClass so you don't need to implement it in any classes that derive from WorkClass.
WorkClass implements the IWork interface so you don't need to implement it in MyClass because it inherits func() from WorkClass.
Since the func method in the abstract class is a non-virtual method, so the compiler thinks this method is a implementation of the interface.
When you extend MyClass to WorkClass, the method func() (which has been defined), is inherited.
So, when the interface IWork is implemented, the method 'func()' has already been defined. So, there are no more undefined methods in MyClass.
So, the class MyClass is a concrete class, due to which you are able to create a MyClass object without any compilation errors.

Difference between abstract class and interface [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Interface vs Base class
I am not understanding the difference between an abstract class and an interface. When do I need to use which art of type?
Try thinking of it like this:
An abstract class creates an "is-a" relationship. Volkswagon is a Car.
An interface creates a "can-do" relationship. Fred can IDrive.
Moreover, Fred can IDrive, but Fred is a Person.
When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
article along with the demo project discussed Interfaces versus Abstract classes.
An abstract class is class probably with some abstract methods and some non-abstract methods. They do stuff (have associated code). If a new non-abstract class, subclasses the abstract class it must implement the abstract methods.
I.E.
public abstract class A {
public string sayHi() { return "hi"; } // a method with code in it
public abstract string sayHello(); // no implementation
}
public class B
: A
{
// must implement, since it is not abstract
public override string sayHello() { return "Hello from B"; }
}
Interface is more like a protocol. A list of methods that a class implementing that interface must have. But they don't do anything. They have just method prototypes.
public interface A
{
string sayHi(); // no implementation (code) allowed
string sayHello(); // no implementation (code) allowed
}
public class B
: A
{
// must implement both methods
string sayHi() { return "hi"; }
string sayHello() { return "hello"; }
}
Both are often confused because there is no protocol/interface in C++. So the way to simulate an interface behavior in that language is writing a pure virtual class (a class with only pure virtual functions).
class A {
virtual int a() = 0; // pure virtual function (no implementation)
}

Categories

Resources