Jump to content
  • Advertisement
Sign in to follow this  
obi-wan shinobi

Inheritance and overriding...

This topic is 4877 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Do I have no choice but to inherit a class object in order to override one of its methods? Take this code for example...
//using Java
public class letsDraw extends Canvas {

  public void paint(Graphics g) {
    //there be lines and text drawn here
  }

}

It inherits the Canvas class and allows me to override the paint method. However, if I try something like...
//using Java
public class letsDraw {
  Canvas canvas;    //member object of type Canvas

  public void canvas.paint(Graphics g) {
    //there be lines and text drawn here
  }
}

...I get errors even though I thought all I was doing was overriding the method without inheriting it. Although I use Java in the examples above, I'm sure it similarly applies to C++/C# as well. Must I always inherit an object to override its methods or is there some other way?

Share this post


Link to post
Share on other sites
Advertisement
You must derive from a class in order to override any of it's methods. You are saying: "This is a <class>."

Share this post


Link to post
Share on other sites
You can of course define a method with the same name as in the member object, but it will not "override".


public class letsDraw {
private Canvas c;
public void paint(Graphics g) {
// probably you'd want to do this at some point:
c.paint(g);
// and possibly other stuff
}
}

// But this will NOT work:

Canvas myCanvas = new letsDraw(); // error! letsDraw isn't a Canvas
// similarly, any attempt to tell the Java API to treat your class as a Canvas
// (like registering it for repaints or whatever) does not work.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!