Inheritance and overriding...

Started by
2 comments, last by obi-wan shinobi 18 years, 10 months ago
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?
Advertisement
You must derive from a class in order to override any of it's methods. You are saying: "This is a <class>."

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

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.
Thanks for the replies. I'll have to keep this in mind.

This topic is closed to new replies.

Advertisement