Difference between virtual and abstract methods [duplicate] - c#

This question already has answers here:
What is the difference between an abstract method and a virtual method?
(28 answers)
Closed 4 years ago.
Here is some code from MSDN:
// compile with: /target:library
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.
}
}
Can anyone explain the above code with respect to the differences between abstract and virtual methods?

Virtual methods have an implementation and provide the derived classes with the option of overriding it. Abstract methods do not provide an implementation and force the derived classes to override the method.
So, abstract methods have no actual code in them, and (non-abstract) subclasses HAVE TO override the method. Virtual methods can have code, which is usually a default implementation of something, and any subclasses CAN override the method using the override modifier and provide a custom implementation.
public abstract class E
{
public abstract void AbstractMethod(int i);
public virtual void VirtualMethod(int i)
{
// Default implementation which can be overridden by subclasses.
}
}
public class D : E
{
public override void AbstractMethod(int i)
{
// You HAVE to override this method
}
public override void VirtualMethod(int i)
{
// You are allowed to override this method.
}
}

First of all you should know the difference between a virtual and abstract method.
Abstract Method
Abstract Method resides in abstract class and it has no body.
Abstract Method must be overridden in non-abstract child class.
Virtual Method
Virtual Method can reside in abstract and non-abstract class.
It is not necessary to override virtual method in derived but it can be.
Virtual method must have body ....can be overridden by "override keyword".....

Abstract Method:
If an abstract method is defined in a class, then the class should
declare as an abstract class.
An abstract method should contain only method definition, should not
Contain the method body/implementation.
An abstract method must be over ride in the derived class.
Virtual Method:
Virtual methods can be over ride in the derived class but not
mandatory.
Virtual methods must have the method body/implementation along
with the definition.
Example:
public abstract class baseclass
{
public abstract decimal getarea(decimal Radius);
public virtual decimal interestpermonth(decimal amount)
{
return amount*12/100;
}
public virtual decimal totalamount(decimal Amount,decimal principleAmount)
{
return Amount + principleAmount;
}
}
public class derivedclass:baseclass
{
public override decimal getarea(decimal Radius)
{
return 2 * (22 / 7) * Radius;
}
public override decimal interestpermonth(decimal amount)
{
return amount * 14 / 100;
}
}

an abstract method must be call override in derived class other wise it will give compile-time error
and in virtual you may or may not override it's depend if it's good enough use it
Example:
abstract class twodshape
{
public abstract void area(); // no body in base class
}
class twodshape2 : twodshape
{
public virtual double area()
{
Console.WriteLine("AREA() may be or may not be override");
}
}

Related

Why abstract class cannot have Sealed method [duplicate]

This question already has an answer here:
Can we declare sealed method in a class
(1 answer)
Closed 4 years ago.
Code Snippet 1 (Compilation Error) - A.M2() cannot be sealed because it is not an override
abstract class A
{
public abstract void M1();
public sealed void M2()
{
// Do Something
}
}
Code Snippet 2 (Works Fine)
abstract class A
{
public abstract void M1();
public virtual void M2()
{
}
}
class B : A
{
public sealed override void M1()
{
}
public sealed override void M2()
{
}
}
Question - If I am providing the implementation of a method in the Abstract class itself, why would C# not allow me to mark it Sealed, why would it want me to override in the sub class, there after mark it as sealed. I cannot understand this discrepancy
Sealed keyword can only be put on functions that are overridable.
That function you specified, is not declared as a virtual function, and hence is not overridable. Also it does not make any sense for a function to be declared "virtual" and "sealed" as sealed cancels out being "virtual"
Sealed only can be used hand in hand with the "override" keyword, and stops other classes from overriding the functions themselves.
It has nothing to do with an abstract class. You cannot make a method as sealed in any class until it is an override method in derived class.
If you had intentions for restricting it from override in derived class then you better use private access modifier.
And the reason why you could use sealed in derived class; I've an example of it below
You have three classes A,B,C where B overrides A and C derives from B -> B:A, C:B
abstract class A
{
public abstract void MyMethod();
}
class B : A
{
public sealed override void MyMethod()
{
}
}
class C : B
{
public override void MyMethod()
{
}
}
In above example we could override method of A in B class because it is not sealed. But if you override method of B in class C then it is not allowed due to sealed keyword.
It will restrict further overrides from class B. Thats where we can use sealed

Override method from instance of the class

I have a merly simple question, but seems cant find an answer for it, I want to know if its possible to override a method from a instance class structore would look like this:
public class A : baseA
{
public virtual void methodA()
{
}
}
public class B : baseB
{
public void method B()
{
var ClassA = new A();
}
/* Now Is there some sort of overide like */
public override methodA()
{
//Do stuff
}
}
And those classes do not inherit from each other, to make it more difficult.
Now if this sort of construction is possible in c#?
No. You cannot override a class's behavior if you don't inherit from it.
The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.
Class B must inherit from class A in order to do so.
public class A
{
public virtual void methodA()
{
}
}
public class B : A
{
public void methodB()
{
var ClassA = new A();
}
public override void methodA()
{
//Do stuff
}
}
Check MSDN for more details:
An override method provides a new implementation of a member that is inherited from a base class. The method that is overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method

Preventing the virtual and override in inheritance chain

Please note: This is a conceptual question and not related to production specific code.
Suppose we have Class A with virtual method GetBonus(int value)
Next, we derive a class from this called Class B. In this Class B we override the method GetBonus.
Next, we derive a class from Class B called Class C.
Now class C can also override the GetBonus method of class A.
Question:
Whether Class C overrides the method definition of Class A or of the Class B?
In Class C, How can the overriding of the method of Class A be prevented ?
In Class C, How can the overriding of the method of Class B be prevented ?
I know that there is a SEALED keyword for sealing the virtual overridden methods. But above questions will help me clear my doubts.
Questions 2 and 3 boil down to the same thing basically, and sealed is indeed the answer here.
Perhaps you asked it a bit vague, but you can only prevent overriding of virtual methods in derived classes. Not in the derived class itself. In the end, for both questions 2 and 3, you have only one option:
class A
{
public virtual void GetBonus(int value) { }
}
class B : A
{
public sealed override void GetBonus(int value) { } // We seal this method
}
class C : B
{
public override void GetBonus(int value) // This line is invalid
// because it cannot override the sealed member from class B.
{ }
}
This will prevent method GetBonus from getting overridden in derived classes.
This sample also answers question 1. It gives a compilation error because class C's override of GetBonus is attempting to override the version provided by class B and not the one provided by A. This is true because overriding the one from A would obviously work as it isn't sealed.
according to https://msdn.microsoft.com/en-us/library/ms173149%28v=vs.110%29.aspx (take a look at picture)
when you override a virtual method and then derived that class in another class you inherit overriden implementation
class A
{
public virtual void GetBonus(int value)
{
//if you define this method as seald no one can override this
}
}
class B:A
{
public override void GetBonus(int value)
{
}
}
class C:B
{
public override void GetBonus(int value)
{
//here we override implementation of class B
}
}
}

If a virtual method is declared abstract

My friend asks me if an abstract method could have virtual modifier. And I said, No.
Because, an abstract method is implicitly also a virtual method, it cannot have the modifier virtual.
But while reading one of the MSDN articles, I have seen this:
...
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 can't understand first sentence correctly. Could you please, explain me what they wants to say?
Thanks.
It becomes clearer when you look at the code example directly above the quoted paragraph:
public class D
{
public virtual void DoWork(int i)
{
// Original implementation.
}
}
public abstract class E : D
{
public abstract override void DoWork(int i);
}
The virtual method D.DoWork is inherited by E, and, there, declared abstract. The method is still virtual, it has just become abstract as well.
As you correctly state, an abstract method is always virtual. If your friend is still unconvinced, here's an official quote for that:
An abstract method is implicitly a virtual method.
Abstract classes may override virtual members with abstract ones:
public class B
{
public virtual void M() { }
}
public abstract class D : B
{
public abstract override void M();
}
public abstract class D2 : D
{
public override void M() { }
}
The sentence says that D2 must override void M(), because it is declared abstract in D. If it were declared as D2 : B, this would be optional, but as it stands, D2 has to comply with the contracts specified in D, but M() will also behave like any other member overriding a "normal" virtual member, since M() is both virtual and abstract.

An abstract method overrides an abstract method

public abstract class A
{
public abstract void Process();
}
public abstract class B : A
{
public abstract override void Process();
}
public class C : B
{
public override void Process()
{
Console.WriteLine("abc");
}
}
This code throws an Compilation Error: 'B' does not implement inherited abstract member 'A.Process()'.
Is there any way to do this?
Just leave out the method completely in class B. B inherits it anyway from A, and since B itself is abstract, you do not explicitly need to implement it again.
Works for me in VS2008; no errors, no warnings. BUT, there's no reason to have the 'override' in B. This code is equivalent:
public abstract class A
{
public abstract void Process();
}
public abstract class B : A
{
}
public class C : B
{
public override void Process()
{
Console.WriteLine("abc");
}
}
The place where I've seen this sometimes is overriding a non-abstract virtual method with an abstract method. For example:
public abstract class SomeBaseType
{
/* Override the ToString method inherited from Object with an abstract
* method. Non-abstract types derived from SomeBaseType will have to provide
* their own implementation of ToString() to override Object.ToString().
*/
public abstract override string ToString();
}
public class SomeType : SomeBaseType
{
public override string ToString()
{
return "This type *must* implement an override of ToString()";
}
}
Alon -
This makes no sense. First of all, this does actually compile fine. Secondly, the abstract method you declared in A is inherited (still abstract) into B. Therefore, you have no need to declare Process() in class B.
--
Mark

Categories

Resources