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();
}
Related
I have an interface like this
interface IFoo
{
protected abstract int Compute();
int ComputeValue()
{
return Compute();
}
}
The idea being that Compute computes some value and ComputeValue maybe does some checks and then calls Compute to fetch the actual value. However, I now wonder how to implement this interface in an abstract class. I can do it like this
abstract class Bar : IFoo
{
public abstract int Compute();
}
but I dont want Compute to be called directly. However, when I try to implement it explicitly, e.g.
abstract class Bar : IFoo
{
abstract int IFoo.Compute();
}
I cannot define it as abstract in the abstract class Bar, which is what I want. Of course, I could do something like
abstract class Bar : IFoo
{
protected abstract int Compute();
int IFoo.Compute()
{
return Compute();
}
}
But I wonder is there a more elegant way of doing this without the additional extra method?
Not much you can do here. Though according toto the draft spec it was considered at some point to allow the support for explicit interface abstract overrides in classes (also see the reabstraction part):
Because we support explicit abstract overrides in interfaces, we could do so in classes as well
abstract class E : IA, IB, IC // ok
{
abstract void IA.M();
}
Open issue: should we support explicit interface abstract overrides in classes?
But it seems it was not followed through - see LDM-2019-03-27 Notes:
Explicit interface abstract overrides in classes
Allow abstract interface implementions in a class as well? Not an abstract class method implementing an interface method.
So either remove the Compute from the interface or use your current approach.
I was wondering if there are any (runtime) difference if I implement an interface on a derived class if the base abstract class implements it already abstract:
public interface IFoo
{
void Bar();
}
public abstract class Base : IFoo
{
public abstract void Bar();
}
public class Derived : Base, IFoo // does this make any difference?
{
public override void Bar()
{
// do something
}
}
Is there any difference writing the "implemention" IFoo on Derived for example when I check if an instance implements an interface at runtime etc.?
Consider following on your example. Must the following be possible?
void f(Base b){
IFoo ifoo = b;
}
Because an object b is a Base, it must be an IFoo because Base implements IFoo. Now consider the following.
var d = new Derived();
f(d);
Since d is a Derived, it is a Base, because derived inherits from Base. Because of this, we can pass it to f, where it is then assigned to an IFoo, as we did before.
Essentially, because a derived class still is also all of its base classes, it already implements all of its base classes' interfaces. The designers of the language acknowledged this and there is no need to redeclare that a derived class is implementing interfaces that are implemented by its base classes.
I guess that maybe your question arises because of where you actually put the method body, but that really isn't relevant. The declaration of the interface is a contract for other consumers of objects of that type. Those consumers don't care where the method body was defined, all that they care is that when they have an IFoo, that it has a method with the signature void Bar() that can be called, as I showed earlier, inheritance must include all interfaces, so there is no need to declare them again.
The answer is No. There is no difference.
The Class Derived inherits from Base and Base in turn inherits from IFoo.
So, there is no necessity for you to "Implement" both Base and IFoo when defining the class Derived.
The hierarchy is established when you are defining the class Base:
public abstract class Base : IFoo
and continued when you define Derived as below:
public abstract class Derived : Base
The only problem may arise when you "Remove" Base from the hierarchy by redefining the Base class by removing the : IFoo implementation from the Base class definition as below:
public abstract class Base
The bottom line is: , IFoo is redundant and is therefore not necessary.
We know if a class has an abstract method it will be abstract . It can't get an instance. But why can have an instance method? Does it have any meaning?
public abstract class AbsClass
{
public abstract void GetA();
public void Getb()
{ }
}
Not every method in an abstract class has to be abstract - when you derive from the class, the derived classes will inherit the non-abstract methods from the base class. It's extremely common to want to provide functionality in the base class that is common to all the derived classes (in fact, it's good programming practice to pull shared functionality up to the base class to avoid duplicating code in the various derived classes). It's also extremely common to want to provide "default" functionality in the base class that can then be overridden by individual derived classes.
The fact that you can't instantiate the base class itself doesn't matter - the non-abstract methods from the base class are called on instances of (non-abstract) derived classes.
Yes, it has a meaning.
It will be available for use in any derived class that does not explicitly implement it itself.
Example of a derived class:
public abstract class AbsClass
{
public abstract void GetA();
public void Getb()
{ }
}
public class DerivedClass : AbsClass
{
}
The following code will execute the abstract class's Getb() code:
var derivedClass = new DerivedClass();
derivedClass.Getb();
(Note that in the example above, the code wouldn't compile unless your derived class implemented GetA(), as it's declared as abstract, and therefore must be implemented in any concrete derived class)
Yes, it is perfectly well defined. It can't be invoked until you have an instance, which in turn indicates that you must have a concrete sub-type, but once you do the method is perfectly usable, for example:
AbsClass foo = new ConcreteClass();
foo.Getb();
Or indeed:
ConcreteClass foo = new ConcreteClass();
foo.Getb();
(since the sub-type inherits any types defined on base-types)
It is quite common for such methods to themselves use the abstract or virtual methods of the type - or indeed to be virtual.
The method will be the implementation for a concrete class that derives from AbsClass. Abstract means you can't create an instance of the class, not that it can't have any methods with implementation. You can also have instance data members in an abstract class.
As an example:
public class MyAbsClass : AbsClass
{
}
MyAbsClass mine = new MyAbsClass();
mine.Getb(); //This would call the implementation in AbsClass
If AbsClass were an interface, however, no implementation would be allowed.
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.
I have an interface so class writers are forced to implement certain methods. I also want to allow some default implemented methods, so I create a abstract class. The problem is that all classes inherit from the base class so I have some helper functions in there.
I tried to write : IClass in with the abstract base, but I got an error that the base didn't implement the interface. Well of course because I want this abstract and to have the users implement those methods. As a return object if I use base I can't call the interface class methods. If I use the interface I can't access base methods.
How do I make it so I can have these helper classes and force users to implement certain methods?
Make sure methods in the base class have the same name as the interface, and they are public. Also, make them virtual so that subclasses can override them without hiding them.
interface IInterface {
void Do();
void Go();
}
abstract class ClassBase : IInterface {
public virtual void Do() {
// Default behaviour
}
public abstract void Go(); // No default behaviour
}
class ConcreteClass : ClassBase {
public override void Do() {
// Specialised behaviour
}
public override void Go() {
// ...
}
}
Move the interface methods into the abstract class and declare them abstract as well. By this, deriving classes are forced to implement them. If you want default behaviour, use abstract classes, if you want to only have the signature fixed, use an interface. Both concepts don't mix.
Having faced with the same problem recently, I've came up with a somewhat more elegant (to my mind) solution. It looks like:
public interface IInterface
{
void CommonMethod();
void SpecificMethod();
}
public abstract class CommonImpl
{
public void CommonMethod() // note: it isn't even virtual here!
{
Console.WriteLine("CommonImpl.CommonMethod()");
}
}
public class Concrete : CommonImpl, IInterface
{
void SpecificMethod()
{
Console.WriteLine("Concrete.SpecificMethod()");
}
}
Now, according to C# spec (13.4.4. Interface mapping), in the process of mapping IInterface on Concrete class, compiler will look up for CommonMethod in CommonImpl too, and it doesn't even have to be virtual in the base class!
The other significant advantage, compared to Mau's solution, is that you don't have to list every interface member in the abstract base class.