I have a question about how one of these methods is called. The call
theNote.Write() ;
uses the Write() method in the Document class, and not the Write()
from the Note class. Why is this? theNote is a Note type, isn't it? So
shouldn't it call the method from the derived class? Or does it have
something to do with the fact that the Write() method in Note uses the
new keyword?
Basically, I understand how Read() is overridden, but I don't
understand how the Write() method is being called in this example.
The code:
-----------------
#region Using directives
using System;
using System.Collecti ons.Generic;
using System.Text;
#endregion
namespace overridingInter face
{
interface IStorable
{
void Read();
void Write();
}
// Simplify Document to implement only IStorable
public class Document : IStorable
{
// the document constructor
public Document( string s )
{
Console.WriteLi ne(
"Creating document with: {0}", s );
}
// Make read virtual
public virtual void Read()
{
Console.WriteLi ne(
"Document Read Method for IStorable" );
}
// NB: Not virtual!
public void Write()
{
Console.WriteLi ne(
"Document Write Method for IStorable" );
}
}
// Derive from Document
public class Note : Document
{
public Note( string s ):
base(s)
{
Console.WriteLi ne(
"Creating note with: {0}", s );
}
// override the Read method
public override void Read()
{
Console.WriteLi ne(
"Overriding the Read method for Note!" );
}
// implement my own Write method
public new void Write()
{
Console.WriteLi ne(
"Implementi ng the Write method for Note!" );
}
}
public class Tester
{
static void Main()
{
// create a document object
Document theNote = new Note( "Test Note" );
IStorable isNote = theNote as IStorable;
if ( isNote != null )
{
isNote.Read();
isNote.Write();
}
Console.WriteLi ne( "\n" );
// direct call to the methods
theNote.Read();
theNote.Write() ;
Console.WriteLi ne( "\n" );
// create a note object
Note note2 = new Note( "Second Test" );
IStorable isNote2 = note2 as IStorable;
if ( isNote2 != null )
{
isNote2.Read();
isNote2.Write() ;
}
Console.WriteLi ne( "\n" );
// directly call the methods
note2.Read();
note2.Write();
}
}
} 6 1379
"John Salerno" wrote... I have a question about how one of these methods is called. The call
theNote.Write() ;
uses the Write() method in the Document class, and not the Write() from the Note class. Why is this? theNote is a Note type, isn't it? So shouldn't it call the method from the derived class? Or does it have something to do with the fact that the Write() method in Note uses the new keyword?
When a method not is constructed with the virtual keyword in the base class,
it simply looks in the "method list" for the declared type of the
*variable*, not the type for the instance.
In the test program:
Document theNote = new Note( "Test Note" );
....which means that non-overridden (non-virtual) methods will use the
implementation of Document, not implementations in the subclass.
Personally, I think it was a mistake from Microsoft's part to limit the
possibilities of polymorphism this way...
// Bjorn A
When you declare a method as "virtual", what you're telling the
compiler is that you want to defer until run-time the decision about
which method (from which level in the class hierarchy) should really be
called when you say, for example, "Read()".
If you don't declare a method "virtual" then you are saying that the
compiler should make the final decision about which method should be
called.
Now, here you have to make a careful distinction between compile time
and run time, between what the compiler knows (which is limited), and
what is the reality when the code is running. When you say,
Document theNote = new Note("Test Note");
you are telling the compiler that theNote is a Document. Now, at run
time, the CLR will know that it is really a particular kind of Document
called a Note, but that is only because it has the real, instantiated
Note at its disposal (because it's running the code). The compiler
couldn't figure that out without... well, it just couldn't.
So, the compiler thinks that theNote is a Document. Since Write() isn't
virtual, you've left it up to the compiler to decide which method to
call, so it calls Document.Write( ).
In the case of Read(), which is virtual, the compiler defers the
decision to the run-time. It says, "Call the Read() method of the type
of the object that theNote points to". At run time, theNote points to a
Note, so the run time decides to call Note.Read(). Again, because you
declared it virtual.
To Bjorn I would add, no, it wasn't a mistake. It was an efficiency
decision. Virtual methods cause increased memory consumption and slower
execution. Not much, but over millions of method calls and millions of
objects, it all adds up. Java's solution was to assume that everything
is virtual unless you specifically state otherwise. The MS team noted
that most programmers don't bother, so they took the opposite tack: you
get virtual methods only when you explicitly state that you want them.
This doesn't "limit polymorphism" in any way. It just means that you
don't get it unless you ask for it.
Jeff Louie wrote: This may help:
Chapter 8 "Shadow Fields, Override Virtual Methods"
http://www.geocities.com/jeff_louie/OOP/oop8.htm
Regards, Jeff
Or does it have something to do with the fact that the Write() method
in Note uses thenew keyword? <
*** Sent via Developersdex http://www.developersdex.com ***
Thanks guys. I think I need to read up a bit more about OOP specifically.
John Salerno <jo******@NOSPA Mgmail.com> wrote: I have a question about how one of these methods is called. The call
theNote.Write() ;
uses the Write() method in the Document class, and not the Write() from the Note class. Why is this? theNote is a Note type, isn't it? So shouldn't it call the method from the derived class? Or does it have something to do with the fact that the Write() method in Note uses the new keyword?
Absolutely. You're not overriding Document.Write in Note, you're
creating a new method which also happens to be called Note. That isn't
visible to theNote, as the type of the theNote variable is Document.
See http://www.pobox.com/~skeet/csharp/faq/#override.new
--
Jon Skeet - <sk***@pobox.co m> http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jon Skeet [C# MVP] wrote: John Salerno <jo******@NOSPA Mgmail.com> wrote:
I have a question about how one of these methods is called. The call
theNote.Write ();
uses the Write() method in the Document class, and not the Write() from the Note class. Why is this? theNote is a Note type, isn't it? So shouldn't it call the method from the derived class? Or does it have something to do with the fact that the Write() method in Note uses the new keyword?
Absolutely. You're not overriding Document.Write in Note, you're creating a new method which also happens to be called Note. That isn't visible to theNote, as the type of the theNote variable is Document.
See http://www.pobox.com/~skeet/csharp/faq/#override.new
Great link. That helped a lot to explain it, and I'm sure the other
questions will be great to read as well. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: scooter |
last post by:
Given this class heirarchy
class Base{};
class A : public Base
{};
class B : public Base
{};
|
by: DJ.precario |
last post by:
In a schematic way, I have a program with a virtual base class
(MyClass), and some derived classes (MyClass1, Myclass2...)
In main, I want to create a vector of objects of the classes that
derive from MyClass. My question is:
-Can I have such a vector with actual objects of different kinds but
all deriving from MyClass or does it have to be a vector of pointers to
such objects?
|
by: John Salerno |
last post by:
Along with events and delegates, polymorphism has been something I sort
of struggle with every now and then. First, let me quote the book I'm
reading:
"Polymorphism is most useful when you have two or more derived classes
that use the same base class. It allows you to write generic code that
targets the base class rather than having to write specific code for
each object type."
And here is the example in the book:
|
by: relient |
last post by:
Hi, I just started the chapter on "Inheritance" and I'm a bit confused
so I have three questions: first, here's the code:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleProject1
{
public class Base
|
by: davetelling |
last post by:
I am not a programmer, I'm an engineer trying to make an interface to a
product I'm designing. I have used C# to make a form that interrogates the
unit via the serial port and receives the data. I want to be able to draw
lines in a picturebox based upon certain data points I have received. I
dragged a picturebox from the toolbar onto my form, but after having gone
through the help files, looking online and trying a variety of things, I...
| |
by: James Crosswell |
last post by:
I'm not sure if I'm going about this the right way - it may be that
Generics might be able to help me out here... but here goes:
I have three classes as follows
class BaseEdit
class WidgetEdit: BaseEdit
class FooEdit: BaseEdit
These are all acutally Windows Forms and BaseEdit is an abstract class
(and so never gets instantiated). I'd like to define a method in
|
by: Markus Svilans |
last post by:
Hello,
My question involves virtual functions and inheritance.
Suppose we have a class structure, that consists of "data" classes, and
"processor" classes. The data classes are derived from BufferBase, and
customized in order to be able to a type of data (of any kind, such as
chunks of audio samples from a sound card). The processor classes are
derived from ProcessorBase, and are customized to handle
BufferBase-derived objects. Each...
|
by: C.L. |
last post by:
I was looking for a function or method that would return the index to the first
matching element in a list. Coming from a C++ STL background, I thought it might
be called "find". My first stop was the Sequence Types page of the Library
Reference (http://docs.python.org/lib/typesseq.html); it wasn't there. A search
of the Library Reference's index seemed to confirm that the function did not
exist. A little later I realized it might be called...
|
by: Jon Skeet [C# MVP] |
last post by:
On Aug 11, 5:11 am, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:
Exactly. My favourite example is Thread.Sleep. Suppose this code were
valid (its equivalent in Java is, for example):
ThreadStart ts = SomeMethodToRun;
Thread thread = new Thread(ts);
thread.Start();
thread.Sleep(500);
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |