How to call the subclass's method?

  • Thread starter Thread starter Quentin Huo
  • Start date Start date
Q

Quentin Huo

Hi,

I created a class "myClass" and another class "mySubclass" which inherited
from "myClass". In the "mySubclass", there is a public method named
"methodOfSubclass(...)" which is not defined in "myClass".

In a client program I tried to call the "methodOfSubclass(...)", like

.......
myClass mc;
mc = new mySubclass();
mc.methodOfSubclass(...);
.......

but I got an error message when I tried to compile it:

'...myClass' does not contain a definition for 'methodOfSubclass'

What is the problem? Do I have to create a virtual method
"methodOfSubclass(...)" in "myClass" and override it in "mwSubclass"? Any
other solutions?

Thanks

Q.
 
If the method is unique to the subclass you may not want it virtual as other
subclasses may not need it. Have you tried to cast the object to the
subclass type like this:

mySubclass msc = (mySubclass)mc;
msc.methodOfSubclass();
 
but I got an error message when I tried to compile it:

'...myClass' does not contain a definition for 'methodOfSubclass'

What is the problem?

Exactly what the error message says.

Do I have to create a virtual method
"methodOfSubclass(...)" in "myClass" and override it in "mwSubclass"?

That's one way to do it. If it makes sense for the base class to have
such a method.

Any other solutions?

((mySubclass)mc).methodOfSubclass(...);



Mattias
 
"Quentin Huo" ...
......
myClass mc;
mc = new mySubclass();
mc.methodOfSubclass(...);
......

but I got an error message when I tried to compile it:

'...myClass' does not contain a definition
for 'methodOfSubclass'

What is the problem? Do I have to create a virtual method
"methodOfSubclass(...)" in "myClass" and override it in
"mwSubclass"?

That's one way...
Any other solutions?

The type of the variable controls what you can access through it. The *only*
things you can access is what is defined in the variable's type, which can
be a class or an interface.

The simplest is to let the variable be of the subclass type from the
beginning.

mySubclass mc;
mc = new mySubclass();
mc.methodOfSubclass(...);

Another way is to cast to another variable of the subclass type:

myclass mc;
mc = new mySubclass();

mySubclass msc = (mySubclass) mc;
mc.methodOfSubclass(...);

Or you can use the "virtual/override" thingy...

// Bjorn A
 
Try something like

if(mc is mySubclass)
{
(mc as mySubclass).methodOfSubclass(...);
}

paul
 
Back
Top