A text from a book which must be wrong(virtual, abstract metod)

T

Tony Johansson

Hello!

I'm reading in a book about C# and here is something that sound strange.

"You can override a virtual method (or accessor) with an abstract method (or
abstract accessor) in a derived class.Any classes derived from this abstract
class must override these abstract methods and provide new implamantations
for them to become non-abstract."

What override a virtual method (or accessor) with an abstract method ??
This must be wrong??

//Tony
 
L

Lasse Vågsæther Karlsen

Tony said:
Hello!

I'm reading in a book about C# and here is something that sound strange.

"You can override a virtual method (or accessor) with an abstract method (or
abstract accessor) in a derived class.Any classes derived from this abstract
class must override these abstract methods and provide new implamantations
for them to become non-abstract."

What override a virtual method (or accessor) with an abstract method ??
This must be wrong??

It is possible to do so, but in my experience not widely used.

One scenario I can come up with is that you have a base class that you
wish to descend from, but you wish to force descendants that implement
functionality to replace a method that the base class have provided a
default implementation for.

Example:

public class LoggerBase
{
public virtual void LogMessage(String s)
{
Debug.WriteLine(s);
}
}

public class YourNewLoggerBase : LoggerBase
{
public abstract override void LogMessage(String s);
}

public class SomeNewLoggingClass : YourNewLoggerBase
{
public override void LogMessage(String s)
{
//
}
}
 
J

Jon Skeet [C# MVP]

Tony Johansson said:
I'm reading in a book about C# and here is something that sound strange.

"You can override a virtual method (or accessor) with an abstract method (or
abstract accessor) in a derived class.Any classes derived from this abstract
class must override these abstract methods and provide new implamantations
for them to become non-abstract."

What override a virtual method (or accessor) with an abstract method ??
This must be wrong??

It's easy enough to show that it's correct:

public class Base
{
public virtual void Foo()
{
}
}

public abstract class Derived : Base
{
public abstract override void Foo();
}

Basically it's saying, "Derived is rejecting the implementation of Foo
in Base - it's not optional to override it in classes derived from
Derived, you *have* to override it."
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top