abstract and a static method (Help)

P

Polo

Hi

I have a abstract class and some other than inherite from it
I woul like to return a bitmap (defined in resource) from the each subclass
(a bitmap that is global (static))

Thank's in advance

public abstract class Segment
{
static public Bitmap GetBitmap()
{
return new Bitmap(....);
}
}

public class SegmantA : Segment
{
....
}


public class SegmantB : Segment
{
.....
}

public class Test
{
static void Main()
{
Bitmap A = SegmentA.GetBitmap();
Bitmap B = SegmentB.GetBitmap();
}
}
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

GetBitmap cannot be static, it has to be virtual

I would suggest you to take a look into OOP concepts.

cheers,
 
M

Martin

Polo said:
Hi

I have a abstract class and some other than inherite from it
I woul like to return a bitmap (defined in resource) from the each subclass
(a bitmap that is global (static))

Thank's in advance

public abstract class Segment
{
static public Bitmap GetBitmap()
{
return new Bitmap(....);
}
}

public class SegmantA : Segment
{
....
}


public class SegmantB : Segment
{
.....
}

public class Test
{
static void Main()
{
Bitmap A = SegmentA.GetBitmap();
Bitmap B = SegmentB.GetBitmap();
}
}

Polo

What you want to do will work. See the following code. I've changed
things so strings are returned instead of Bitmaps but you should get the
idea.

using System;

namespace StaticAbstract
{
class StaticAbstractTest
{
[STAThread]
static void Main(string[] args)
{
string A = SegmentA.GetString();
string B = SegmentB.GetString();

Console.WriteLine(A);
Console.WriteLine(B);

Segment SegA = new SegmentA();
Segment SegB = new SegmentB();

string C = SegA.OverrideMe();
string D = SegB.OverrideMe();

Console.WriteLine(C);
Console.WriteLine(D);
}
}

public abstract class Segment
{
public static string GetString()
{
return "StaticString";
}

public virtual string OverrideMe()
{
return "Base + ";
}
}

public class SegmentA : Segment
{
public override string OverrideMe()
{
return base.OverrideMe() + "SegmentA String";
}

}

public class SegmentB : Segment
{
public override string OverrideMe()
{
return base.OverrideMe() + "SegmentB String";
}

}
}

This gives output of :
-----------------------
StaticString
StaticString
Base + SegmentA String
Base + SegmentB String

If you need to override a method in a subclass, it needs to be marked as
'virtual' in the base class, like I have done here with the method
OverrideMe(), but you are not actually calling a method of the subclass,
you are simply calling the static method held in the base class. Even
though the syntax is SegmentA.GetString() you are actually calling
Segment.GetString()

I hope this is of help.

Best Regards,
Martin
 

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