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)
}
Related
abstract class someClass
{
public abstract IProduct SomeMethod();
}
public interface IProduct
{
string Operation();
}
I have seen the above code having a method define inside abstract class with type interface, I wonder the use of this. Can anybody explain?
You are asking about this:
abstract class SomeBaseClass
{
public abstract IProduct SomeMethod();
}
In this case, IProduct may represent any object that implements the interface, and the method SomeMethod() is guaranteed to return an object of some class implementing IProduct.
This has many uses where the design dictates that all classes that derive from SomeBaseClass be able to create objects that adhere to the IProduct interface.
In c# interfaces are like contracts that guarantee specific behavior and properties.
This means that regardless of the actual implementation, code like this below is valid
SomeBaseClass f = ...
IProduct p = f.SomeMethod();
string op = p.Operation();
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.
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 .
Like Interfaces, can an abstract class have only method signatures without implementation? If yes:
How do abstract classes differ from interfaces?
How can another class, which has an abstract class as its base class, implement the body of the base class methods?
An abstract class can contain implementations, but it doesn't have to. This is one thing that makes it different from interfaces.
abstract class classA
{
abstract public void MethodA();
public void MethodB()
{
Console.WriteLine("This is MethodB inside ClassA");
}
}
class classB : classA
{
public override void MethodA()
{
Console.WriteLine("This is MethodA inside class B");
}
}
If you implement a method in the abstract base class and want to be able to override it later, you need to declare the method as virtual.
virtual protected void MethodC(){
//this can be overridden
}
in Java:
q1: The abstract class can contain method definitions AND normal methods while an interface cannot.
q2: from http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
//this is the abstract class
public abstract class GraphicObject {
abstract void draw();
}
//this is the implementation
class Rectangle extends GraphicObject {
void draw() {
...
}
}
Like Interfaces, can an abstract class have only method signature without implementation? If yes:
Yes, but can also have implementation ...
You can also have method implementation in the abstract class unlike interfaces, but you can not create an instance of an abstract class
Interfaces and Abstract Classes
Abstract Class versus Interface
Like Interfaces, can an abstract class have only method signature without implementation?
Yes. Abstract class can have method implementation.
How it differs from Interface?
Variables declared in an interface is by default final. An abstract class may contain non-final variables.
Members of a interface are public by default. An abstract class can have the usual flavors of class members like private, protected, etc..
Interface is absolutely abstract and cannot be instantiated; An abstract class also cannot be instantiated, but can be invoked if a main() exists.
In comparison with abstract classes, interfaces are slow as it requires extra indirection.
Refer the following links:
http://forums.asp.net/t/1240708.aspx/1
http://java.sys-con.com/node/36250
http://www.codeproject.com/Articles/11155/Abstract-Class-versus-Interface
Interface is a fully abstract class,
Means only signatures, no implementations, no data members.
On the other hand abstract class by defenition needs at least one abstract method.
Also it can have implementations.
And it also can contain data members which will be inherited to its inheritors.
The inheritor needs to implement the abstract method with the same signature in order to implement it
in JAVA Yes,
if you use abstract class this way, then there is no difference between interface and abstract class. what dose abstract class really matter is you can offer common implementation which expect to be inherited by sub class, that's interface is not able to do.
yes, as I said, that abstract class behave the same way as interface, you can just override the methods in sub class
For example:
public abstract class AbstractClassWithoutImplementation {
public abstract String methodA();
}
public class Implementation extends AbstractClassWithoutImplementation {
#Override
public String methodA() {
// TODO Auto-generated method stub
return "Yes";
}
public static void main(String[] args){
Implementation im = new Implementation();
System.out.println(im.methodA());
}
}
An abstract class is a class that cannot be instantiated. It is in between a concrete class (fully implemented) and an interface (not at all implemented).
It can contain regular members (variables, methods etc) that are fully implemented.
It can also contain abstract members that are not implemented. Any member that is not implemented, say a method signature, must be marked abstract.
So to answer your questions:
Like Interfaces, can an abstract class have only method signature without implementation?
Your wording is not clear enough to give a yes or no answer. An abstract class can have implemented methods, and it can have abstract methods that are not implemented which must be marked as abstract. It cannot have methods without implementation unless they are marked abstract.
If yes: How it differs from Interface?
Because it allows implementation of members.
How another class, for which this Abstract Class is acting as a base class, can implement the body of that method?
Simply needs to implement all the abstract members.
public abstract class A
{
public abstract void Test();
}
public class B : A
{
public void Test(){ return; }
}
Like Interfaces, can an abstract class have only method signature without implementation? If yes:
Yes, An abstract class can have all abstract methods even if it has a single abstract method it must be abstract.You can declare a class as abstract even if it doesn't have any abstract method.
How it differs from Interface?
In Interface ALL methods are abstract public bet in Abstract class it is not necessary that .Please read about Interface vs Abstract Class
How another class, for which this Abstract Class is acting as a base class, can implement the body of that method?
If your BaseClass is Abstract and ChildClass is extending Base class you can implement abstract method in ChildClass otherwise make ChildClass abstract also.
public class ChildClass extends BaseClass{
void display(){
/// Your Implementation here
}
}
abstract class BaseClass{
abstract void display();
}
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.