开发者

J2SE Question, constructor auto run?

开发者 https://www.devze.com 2022-12-12 11:43 出处:网络
I have wrote C# few years and start to learn java, today i saw a sample is strange ,which is cannot happen in C#.

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__2D-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.dra开发者_StackOverflow社区wRoundRect(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 ?


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");}
}


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消