Child class as abstract class in C# - c#

I have the following code in my program
public abstract class test
{
public abstract void test1();
public abstract void test2();
public abstract void test3();
}
public abstract class class1 :test
{
public override void test1()
{
string s = "";
}
}
When I change the type of my child class as abstract it build successfully and the error to include the other two methods have gone. if the child class is abstract class, no need to define at least one abstract methods?

If you mark a method as abstract it means that every (concrete) class which inherits it must provide an implementation - it's a contract in a similar way to interface implementation is a contract.
If you mark the child class as abstract also, it means that it can defer implementation to its child class(es).

It compiles fine, because the child class is abstract too.
That means that in order to instantiate an object of that type, you still need to have yet a third class (at least) that inherits from your child class and that implements the full interface (the missing abstract methods from your parent class).
The class hierarchy that you have presented, cannot be instantiated until there is a class that implements all the required methods - that would be something that can be instantiated.

No, this is not neccessary, as it's fine for an abstract class to contain just method headers, and the other method headers from the abstract base class get inherited.

No - you can declare a class abstract without having any abstract methods. It may not make any sense conceptually for an instance of that class to exist, or you may want to ensure that only subclasses of that class can be instantiated (for whatever reason)

Related

C# language purpose of "override" abstract method [duplicate]

Just out of curiosity I tried overriding a abstract method in base class, and method the implementation abstract. As below:
public abstract class FirstAbstract
{
public abstract void SomeMethod();
}
public abstract class SecondAbstract : FirstAbstract
{
public abstract override void SomeMethod();
//?? what sense does this make? no implementaion would anyway force the derived classes to implement abstract method?
}
Curious to know why C# compiler allows writing 'abstract override'. Isn't it redundant? Should be a compile time error to do something like this. Does it serve to some use-case?
Thanks for your interest.
There's a useful example for this on Microsoft Docs - basically you can force a derived class to provide a new implementation for a method.
public class D
{
public virtual void DoWork(int i)
{
// Original implementation.
}
}
public abstract class E : D
{
public abstract override void DoWork(int i);
}
public class F : E
{
public override void DoWork(int i)
{
// New implementation.
}
}
If a virtual method is declared abstract, it is still virtual to any
class inheriting from the abstract class. A class inheriting an
abstract method cannot access the original implementation of the
method—in the previous example, DoWork on class F cannot call DoWork
on class D. In this way, an abstract class can force derived classes
to provide new method implementations for virtual methods.
I find it really useful for ensuring proper ToString() implementation in derived classes. Let's say you have abstract base class, and you really want all derived classes to define meanigful ToString() implementation because you are actively using it. You can do it very elegantly with abstract override:
public abstract class Base
{
public abstract override string ToString();
}
It is a clear signal to implementers that ToString() will be used in base class in some way (like writing output to user). Normally, they would not think about defining this override.
Interestingly enough, the Roslyn version of the C# compiler has an abstract override method in it, which I found odd enough to write an article about:
http://ericlippert.com/2011/02/07/strange-but-legal/
Imagine that SecondAbstract is in the middle of a three-class hierarchy, and it wants to implement some abstract methods from its base FirstAbstract while leaving some other method X to be implemented from its child ThirdAbstract.
In this case, SecondAbstract is forced to decorate the method X with abstract since it does not want to provide an implementation; at the same time, it is forced to decorate it with override since it is not defining a new method X, but wants to move the responsibility of implementing X to its child. Hence, abstract override.
In general, the concepts modelled by abstract and override are orthogonal. The first forces derived classes to implement a method, while the second recognizes that a method is the same as specified on a base class and not a new one.
Therefore:
neither keyword: "simple" method
abstract only: derived class must implement
override only: implementation of method defined in base class
abstract override: derived class must implement a method defined in base class
This is done because in child class you can not have abstract method with same name as in base class. override tells compiler that you are overriding the behavior of base class.
Hope this is what you are looking for.
If you did not declare SomeMethod as abstract override in SecondAbstract, the compiler would expect that class to contain an implementation of the method. With abstract override it is clear that the implementation should be in a class derived from SecondAbstract and not in SecondAbstract itself.
Hope this helps...
This design pattern is known as the Template Method pattern.
Wikipedia page on Template Methods
A simple, non-software example: There are a bunch of military units: tanks, jets, soldiers, battleships, etc. They all need to implement some common methods but they will implement them very differently:
Move()
Attack()
Retreat()
Rest()
etc...

Why do abstract classes need to define abstract methods from interfaces they implement?

When an abstract class implements an interface, it is required to also either define or declare the methods (as asked before):
public interface MyInterface
{
void Method();
}
public abstract class MyAbstractClass : MyInterface
{
public abstract void Method(); // required, even though MyAbstractClass does not implement
}
public class MyClass : MyAbstractClass
{
public override void Method()
{
}
}
public interface MyInterface2 : MyInterface
{
// no need to declare Method() -- why can't abstract classes do the same for unimplemented methods?
}
What is the design rationale of the c# language to require the definition of abstract methods of abstract classes that implement interfaces? It seems completely redundant for an abstract class to be required to define a method that it does not implement (and to make it even worse, for the class that actually implements the method to have to mark the method as override). I see no reason why an abstract class could not behave like MyInterface2, which inherits from MyInterface but does not need to declare MyInterface's methods.
An abstract class is a fully-fledged type, just except it cannot be instantiated. Hence its full contract must be declared even though some of its methods are not implemented. A user of a particular abstract class must be able to bind to all its methods, be they coming from interfaces or directly declared in the abstract class. It the methods from interfaces were not (at least) declared (if not even implemented) in the abstract class, the used couldn't bind to them.
Further, classes and interfaces are somewhat loosely-coupled. A class may declare a method, which is later mapped to a same-signature method in an interface which is implemented by its descendant. Hence it is again a “good idea” from the language-design viewpoint to require all methods of interfaces being directly implemented on an abstract class to be actually declared in it.
You can think of an interface as a detachable feature (except when explicit implementations are used). The abstract class may live on its own and its direct users need not to know of any of its interfaces.
It's a design feature that only virtual methods can be left without an implementation, because the technical mechanism of virtual methods needs to be leveraged for the whole concept of abstract classes work in practice.
UPDATE: Example:
public interface IFoo { void M(); }
public abstract class Bar : IFoo
{
public virtual abstract void M();
public void N() { }
}
public class Baz : Bar
{
public override void M() { … }
}
…
public void Method(Bar par)
{
par.M();
}
…
Baz x = new Baz();
Method(x);
The Method see the instance denoted by the variable x as Bar — neither as Baz nor as IFoo. In other words, the user of class Bar does not care of whether it implemented one, two, ten, or no interface at all. All it does is access its members. It rely's on Bar's contract, not of IFoos contract. Hence if Bar implements IFoo, it must define all members from IFoo.
A method you create in an abstract class that implements the interface doesn't need to be abstract. Abstract classes can contain non-abstract methods too and you can define a full implementation of the interface there. The inheriting classes wouldn't need to override any of those methods.
Also, this is described in MSDN for abstract classes:
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.
Notice the word "might", it's not "has to".
Please also note what MSDN says about implementing an interface:
When a class or struct implements an interface, the class or struct must provide an implementation for all of the members that the interface defines.
This is true for all kinds of classes and structures.
A class which implements IFoo with method void Bar() has the option of whether or not it wishes to expose a public method Bar(), or whether it wishes to use a non-public member to implement the interface [C# requires the direct implementation method to be either public or private; vb.net also allows protected scope, which is often the most useful sort for abstract classes].
There are two useful ways via which an abstract class could implement IFoo.Bar():
public abtract void Bar();
// or
protected abstract void IFoo_Bar(); // Note that the exact name is arbitrary
void IFoo.Bar() { IFoo_Bar(); }
Both implementations are reasonable. The first would make an unjustified presumption that a class would want to have a public method which appears nowhere in its code; the latter would require the compiler to 'guess' at what name should be given to the abstract method. Because there is no behavior which would be clearly better than any alternative, C# requires the programmer to specify which behavior is desired.

Abstraction Vs. Interface Confusion

Wait, before you start thinking, I would like to clear that I am NOT going to ask the routine differences between Interface and Abstract.
I had gone through the difference between Abstract and Interface in MSDN.
It is said :
By updating the base class, all inheriting classes are automatically updated with the change.
Interfaces, on the other hand, cannot be changed once created. If a new version of
an interface is required, you must create a whole new interface.
See this : -
Can anyone prove this using following example: -
abstract class WashingMachine
{
abstract public void Wash();
}
class Philips : WashingMachine
{
public Philips() { }
override public void Wash(){//Wash code here....}
}
class Samsung : WashingMachine
{
public Samsung() { }
override public void Wash(){//Wash code here....}
}
class Videocon : WashingMachine
{
public Videocon() { }
override public void Wash(){//Wash code here....}
}
Now, If I added following new abstract method in WashingMachine : -
abstract public void Rinse(int loadSize);
How all inheriting classes (i.e. Philips/Samsung/Videocon) will automatically get updated with the change?
They won't get updated - you still have to manually add an implementation of Rinse to each and every class that inherits from WashingMachine.
What I believe the MSDN says is that if you have a non-abstract method defined in an abstract class and you change that method, all classes that inherit from the abstract class will benefit from the change automatically.
Your concrete derived types all need to provide an implementation of any inherited abstract member...thus your types will still need to provide a Rinse implementation when you modified the base.
http://msdn.microsoft.com/en-us/library/sf985hc5(v=vs.71).aspx
This is a confusion programmers normally get when read difference between interface and abstract class. the line you refer is only true if the change in the abstract class is concrete. what i mean is you added a property or a method with implementation. Or if i am more specific, any change in base abstract class which does not make any concrete class abstract. Such change is possible in abstract classes and there is no way you can add such change in interface.
How all inheriting classes (i.e. Philips/Samsung/Videocon) will automatically get updated with the change?
They will suddenly become non-compileable, isn't that an update?
But I'd like to point out that there's in fact no difference between abstract method in abstract class and method in interface. Main difference lies in the fact that abstract classes can have methods with implementation and interfaces can not.
In fact, I'd say that I don't like MSDN definition and find it confusing and somewhat misleading.

What is the use of 'abstract override' in C#?

Just out of curiosity I tried overriding a abstract method in base class, and method the implementation abstract. As below:
public abstract class FirstAbstract
{
public abstract void SomeMethod();
}
public abstract class SecondAbstract : FirstAbstract
{
public abstract override void SomeMethod();
//?? what sense does this make? no implementaion would anyway force the derived classes to implement abstract method?
}
Curious to know why C# compiler allows writing 'abstract override'. Isn't it redundant? Should be a compile time error to do something like this. Does it serve to some use-case?
Thanks for your interest.
There's a useful example for this on Microsoft Docs - basically you can force a derived class to provide a new implementation for a method.
public class D
{
public virtual void DoWork(int i)
{
// Original implementation.
}
}
public abstract class E : D
{
public abstract override void DoWork(int i);
}
public class F : E
{
public override void DoWork(int i)
{
// New implementation.
}
}
If a virtual method is declared abstract, it is still virtual to any
class inheriting from the abstract class. A class inheriting an
abstract method cannot access the original implementation of the
method—in the previous example, DoWork on class F cannot call DoWork
on class D. In this way, an abstract class can force derived classes
to provide new method implementations for virtual methods.
I find it really useful for ensuring proper ToString() implementation in derived classes. Let's say you have abstract base class, and you really want all derived classes to define meanigful ToString() implementation because you are actively using it. You can do it very elegantly with abstract override:
public abstract class Base
{
public abstract override string ToString();
}
It is a clear signal to implementers that ToString() will be used in base class in some way (like writing output to user). Normally, they would not think about defining this override.
Interestingly enough, the Roslyn version of the C# compiler has an abstract override method in it, which I found odd enough to write an article about:
http://ericlippert.com/2011/02/07/strange-but-legal/
Imagine that SecondAbstract is in the middle of a three-class hierarchy, and it wants to implement some abstract methods from its base FirstAbstract while leaving some other method X to be implemented from its child ThirdAbstract.
In this case, SecondAbstract is forced to decorate the method X with abstract since it does not want to provide an implementation; at the same time, it is forced to decorate it with override since it is not defining a new method X, but wants to move the responsibility of implementing X to its child. Hence, abstract override.
In general, the concepts modelled by abstract and override are orthogonal. The first forces derived classes to implement a method, while the second recognizes that a method is the same as specified on a base class and not a new one.
Therefore:
neither keyword: "simple" method
abstract only: derived class must implement
override only: implementation of method defined in base class
abstract override: derived class must implement a method defined in base class
This is done because in child class you can not have abstract method with same name as in base class. override tells compiler that you are overriding the behavior of base class.
Hope this is what you are looking for.
If you did not declare SomeMethod as abstract override in SecondAbstract, the compiler would expect that class to contain an implementation of the method. With abstract override it is clear that the implementation should be in a class derived from SecondAbstract and not in SecondAbstract itself.
Hope this helps...
This design pattern is known as the Template Method pattern.
Wikipedia page on Template Methods
A simple, non-software example: There are a bunch of military units: tanks, jets, soldiers, battleships, etc. They all need to implement some common methods but they will implement them very differently:
Move()
Attack()
Retreat()
Rest()
etc...

Constructor of an abstract class in C#

Why is it possible to write constructor for an abstract class in C#?
As far as I know we can't instantiate an abstract class.. so what is it for?
You can't instantiate the class, right?
Because there might be a standard way you want to instantiate data in the abstract class. That way you can have classes that inherit from that class call the base constructor.
public abstract class A{
private string data;
protected A(string myString){
data = myString;
}
}
public class B : A {
B(string myString) : base(myString){}
}
Far as I know we can't instantiate an abstract class
There's your error right there. Of course you can instantiate an abstract class.
abstract class Animal {}
class Giraffe : Animal {}
...
Animal animal = new Giraffe();
There's an instance of Animal right there. You instantiate an abstract class by making a concrete class derived from it, and instantiating that. Remember, an instance of a derived concrete class is also an instance of its abstract base class. An instance of Giraffe is also an instance of Animal even if Animal is abstract.
Given that you can instantiate an abstract class, it needs to have a constructor like any other class, to ensure that its invariants are met.
Now, a static class is a class you actually cannot instantiate, and you'll notice that it is not legal to make an instance constructor in a static class.
It's a way to enforce a set of invariants of the abstract class. That is, no matter what the subclass does, you want to make sure some things are always true of the base class... example:
abstract class Foo
{
public DateTime TimeCreated {get; private set;}
protected Foo()
{
this.TimeCreated = DateTime.Now;
}
}
abstract class Bar : Foo
{
public Bar() : base() //Bar's constructor's must call Foo's parameterless constructor.
{ }
}
Don't think of a constructor as the dual of the new operator. The constructor's only purpose is to ensure that you have an object in a valid state before you start using it. It just happens to be that we usually call it through a new operator.
Key Points About Abstract Class
An abstract class cannot be instantiated.
An abstract class can have constructor and destructor.
An abstract class cannot be a sealed class because the sealed
modifier prevents a class from being inherited.
An abstract class contains abstract as well as non-abstract members.
An abstract class members can be private, protected and internal.
Abstract members cannot have a private access modifier.
Abstract members are implicitly virtual and must be implemented by a
non-abstract derived class.
Adding to the above answers and examples.
Yes, an abstract class can have a constructor, even though an abstract class cannot be instantiated. An abstract class constructor c# code example will be explained. But, the next question can also be arises, as if we cannot instantiate (construct an object using new) an abstract class, then what for a constructor is in an abstract class or why should we use a constructor in abstract class?
Note that when we create an object of a derived class then the constructor of the abstract base class is implicitly called, even though we cannot instantiate an abstract class. For example in the program, if we create an object of a derived class then the abstract base class constructor will also be called.
This is also one of the example
Examples
abstract class A
{
protected A() {Console.WriteLine("Abstract class constructor"); }
}
//Derived class
class B : A
{
public B() {Console.WriteLine("Derived class constructor"); }
}
class Program
{
static void Main(string[] args)
{
B obj = new B();
}
}
Output will be
Abstract class constructor
Derived class constructor
It's there to enforce some initialization logic required by all implementations of your abstract class, or any methods you have implemented on your abstract class (not all the methods on your abstract class have to be abstract, some can be implemented).
Any class which inherits from your abstract base class will be obliged to call the base constructor.
Normally constructors involve initializing the members of an object being created. In concept of inheritance, typically each class constructor in the inheritance hierarchy, is responsible for instantiating its own member variables. This makes sense because instantiation has to be done where the variables are defined.
Since an abstract class is not completely abstract (unlike interfaces), it is mix of both abstract and concrete members, and the members which are not abstract are needed to be initialized, which is done in abstract class's constructors, it is necessary to have constructors in the abstract class. Off course the abstract class's constructors can only be called from the constructors of derived class.
You are absolutely correct. We cannot instantiate an abstract class because abstract methods don't have any body i.e. implementation is not possible for abstract methods. But there may be some scenarios where you want to initialize some variables of base class.
You can do that by using base keyword as suggested by #Rodrick. In such cases, we need to use constructors in our abstract class.
You can instantiate it after you implemented all the methods. Then the constructor will be called.
I too want to make some shine on abstract surface
All answer has covered almost all the things. Still my 2 cents
abstract classes are normal classes with A few exceptions
You any client/Consumer of that class can't create object of that
class, It never means that It's constructor will never call. Its derived class can choose which constructor to call.(as depicted in some answer)
It may has abstract function.
Defining a constructor with public or internal storage class in an inheritable concrete class Thing effectively defines two methods:
A method (which I'll call InitializeThing) which acts upon this, has no return value, and can only be called from Thing's CreateThing and InitializeThing methods, and subclasses' InitializeXXX methods.
A method (which I'll call CreateThing) which returns an object of the constructor's designated type, and essentially behaves as:
Thing CreateThing(int whatever)
{
Thing result = AllocateObject<Thing>();
Thing.initializeThing(whatever);
}
Abstract classes effectively create methods of only the first form. Conceptually, there's no reason why the two "methods" described above should need to have the same access specifiers; in practice, however, there's no way to specify their accessibility differently. Note that in terms of actual implementation, at least in .NET, CreateThing isn't really implemented as a callable method, but instead represents a code sequence which gets inserted at a newThing = new Thing(23); statement.
an abstract class can have member variables that needs to be initialized,so they can be initialized in the abstract class constructor and this constructor is called when derived class object is initialized.
From https://msdn.microsoft.com/en-us/library/ms182126.aspx
Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type, and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed.
Since only derived classes can use an abstract class constructor then an abstract class constructor, if needed, must be declared as protected.
However, that said VS compiler will not complain (with default rules) when declaring public constructors in abstract classes however it will not allow creating a new instance.
There are two following important features that prevent to inherit Abstract class
Abstract class must have an abstract method otherwise it is not a abstract class
Abstract class must be inherited by derived class,So if a class inherited by other class than what is use of to create object of that class

Categories

Resources