tags:

views:

59

answers:

3

I have wrote C# few years and start to learn java, today i saw a sample is strange ,which is cannot happen in C#.
from http://www.java2s.com/Tutorial/Java/0261%5F%5F2D-Graphics/Drawrectangles.htm

public class MainClass extends JFrame {

  public static void main(String[] a){
    MainClass f = new MainClass();
    f.setSize(300,300);
    f.setVisible(true);
  }


  public void paint(Graphics g) {
    g.drawRect(10, 10, 60, 50);
    g.fillRect(100, 10, 60, 50);
    g.drawRoundRect(190, 10, 60, 50, 15, 15);
    g.fillRoundRect(70, 90, 140, 100, 30, 40);
  }
}

the constructor paint() will be fire on main(), and the parameter - "g" haven't initialize anythings, is it a hidden feature on java but which is not legal on OOP ?

+4  A: 

What should be illegal here? You are extending a JFrame and only overriding the method paint() (method, not constructor). There rest is all inherited behaviour.

If you check the source code of JFrame and its ancestors you will see that at some point the call to setVisibile() will call paint(). And also provides a correct Graphics object.


The behavior is the same as in this mini example. Which will output "Bar" on the command line. Which makes sense. You override the runMe() method which is called in the constructor of Foo which you inherit in Bar as you don't override it with/provide your own.

public class Test {
    public static void main(String args[]) {
        new Bar();
    }
}

public class Foo {
    public Foo() { runMe(); }
    public void runMe() { System.out.println("Foo"); }
}

public class Bar extends Foo {
    public void runMe() { System.out.println("Bar");}
}
jitter
thanks you for answer, i never thought it is override , because in C# world it need to state by "overrides" keyword.After i search in java doc,http://java.sun.com/docs/books/tutorial/java/IandI/override.htmli know java can skip the keyword .thanks you for help
SilverNight
Yep but should better add it (`@Override`) so the compiler warns you when you think you overwrite something but actually aren't
jitter
+2  A: 

You need to look at this line

public class MainClass extends JFrame

You're getting lot's of extra function from the JFrame class, including the setting up of the Graphic context.

Note that paint() is not a constructor, it's a method of the class, it's called as a result of the setting of the frame to to be visible.

djna
thanks you very much.
SilverNight
+3  A: 

paint() is not a constructor. paint() is a method which will be called by Swing when it needs to draw the frame you have created.

Try reading a tutorial on Swing and the Javadocs for JFrame.

Phill Sacre
thanks you very much.
SilverNight