• Post Reply Bookmark Topic Watch Topic
  • New Topic

Creating a constructor without private implementations only methods?  RSS feed

 
Gia Mata
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Man I'm lost I saw a somebody create this code below . I thought you can only create a new object using private implementations and then using a constructor to set your arguments inside the parameters of the constructor to the instance variables but how come he created an object without any private implementations and just methods inside the constructor.Can somebody please enlighten me on this one really confuse.


 
Paweł Baczyński
Bartender
Posts: 2077
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Notice that class MyWindow extends JFrame.
So MyWindow has access to any public or protected method of JFrame.

Methods: setSize, setVisible and setTitle are part of JFrame class.

You may call any method of a class in this class' constructor.
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I added code tags to your code: always use them. Don't they make it look better

That code is quite all right.
That code is all wrong.

Both those statements were horrible overexaggerations.

You can call any instance code inside a constructor. [You can call any other sort of code, too.] So the compiler will be quite happy with that sort of code. But you shouldn't.

There is a potential hazard to using those methods. What if somebody subclasses your class and overrides them? You will get unexpected behaviour because the methods are polymorphic (as all instance methods are). There are two ways to avoid that hazard:
  • 1: Call only private methods from the constructor.
  • 2: Call only final methods from the constructor.
  • Those methods are all public and not final.

    I don't like the practice of extending from Swing components. There are some where you have to, for example if you override the paintComponent method on a JPanel. But there is usually no need to subclass a Frame. Instead of saying add(...) you can always say myFrame.add(...).
    I am going to suggest another way to do the same thing. You don't need setTitle because you can set the title via the constructor.There were other problems:
  • 1: setVisible should be called last, otherwise code following it may not be rendered correctly.
  • 2: No setDefaultCloseOperation call.

  • Whoever wrote that code for you didn't format it correctly. They used tabs for indenting, and the placement of the { is inconsistent. Two {s are preceded by a space (right) and one isn't. Also there should be a blank lines between methods/constructors etc.
     
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!