Overloaded constructors, final and assert

I am having some difficulties of using final variables and still have the ability to check parameters in the constructor.
For example take this class:
class MyObject {
final String id;
final String value;
public MyObject(String id, String value) {
assert id != null : "error";
assert value != null : "error";
this.id = value;
this.value = value;
public MyObject(Wrapper wrapper) {
assert wrapper != null : "error";
this(wrapper.getId(), wrapper.getValue());
The above code won't compile because the assert is not allowed before the call to the other constructor.
I cannot do the initializing of variables in a normal method, because I cannot assign to the variables at that point.
I can use a static method that created to object, but is that really a good idea?
Any suggestions?

Generally, assert in parameters of public methods is not recommended.
Assertion is for situations that are even more exceptional than Exceptions,
for example, to detect bugs in the code.
Theoretically, in public methods you don�t have to use assert to verify if the
parameter is null or not null. You have to use if statement and throw
NullPointerException,for example. If the method were private, like your
init( ) method, so that�s ok and you could use assertion.It does not make sense to me why I would use asserts in private methods
and not for public ones. Especially since the same parameters might
end up in a private method anyway.
For me asserts are about pre-conditions, post-conditions and constraints.
I especially find them useful for pre-conditions and making very clear
to the caller what I expect of him.
A good article about assert can be found at javaworld
http://www.javaworld.com/javaworld/jw-12-2001/jw-1214-assert.html
Anyway, it's kinda off-topic, because if I would use an if statement
and throw an exception, I have the exact same problem!
This does not compile:
public MyObject(Wrapper wrapper) {
    if (wrapper != null)
        throw NullPointerException("error");
    this(wrapper.getId(), wrapper.getValue());
}

Similar Messages

  • Overloaded constructors & getters and setters problem

    I'm writing a driver class that generates two cylinders and displays some data. Problem is I don't understand the concept on overloaded constructors very well and seem to be stuck. What I'm trying to do is use an overloaded constructor for cylinder2 and getters and setters for cylinder1. Right now both are using getters and setters. Help would be appreciated.
    Instantiable class
    public class Silo2
        private double radius = 0;
        private double height = 0;
        private final double PI = 3.14159265;
        public Silo2 ()
            radius = 0;
            height = 0;       
       // Overloaded Constructor?
       public Silo2(double radius, double height) {     
          this.radius = radius;
          this.height = height;
       // Getters and Setters
       public double getRadius() {
          return radius;
       public void setRadius(double radius) {
          this.radius = radius;
       public double getHeight() {
          return height;
       public void setHeight(double height) {
          this.height = height;
       public double calcVolume()
           return PI * radius * radius * height;
       public double getSurfaceArea()
           return 2 * PI * radius * radius + 2 * PI * radius * height;
    Driver class I'm not going to show all the code as it's rather long. Here's snippets of what I have so far
    So here's input one using setters
    validateDouble reads from a public double method that validates the inputs, which is working fine.
    public static void main (String [ ]  args)
                Silo2 cylinder1 = new Silo2(); 
                Silo2 cylinder2 = new Silo2();
                //Silo inputs           
                double radSilo1 = validateDouble("Enter radius of Silo 1:", "Silo1 Radius");
                cylinder1.setRadius(radSilo1);
                double heiSilo1 = validateDouble("Enter height of Silo 1:", "Silo1 Height");
                cylinder1.setHeight(heiSilo1);
    Output using getters
    //Silo1 output
                JOptionPane.showMessageDialog(null,"Silo Dimensions 1 "   +
                    '\n' + "Radius = " + formatter.format(cylinder1.getRadius()) +
                    '\n' + "Height = " + formatter.format(cylinder1.getHeight()) +
                    '\n' + "Volume = " + formatter.format(cylinder1.calcVolume()) +
                    '\n' + "Surface Area = " + formatter.format(cylinder1.getSurfaceArea()));How can I apply an overloaded constructor to cylinder2?
    Edited by: DeafBox on May 2, 2009 12:29 AM

    DeafBox wrote:
    Hey man,
    My problem is that I don't now how to use an overloaded constructor. I'm new to this concept and want to use an overloaded contructor to display data for cylinder2, and getters and setters to display data for cylinder1.So, again, what in particular is your problem?
    Do you not know how to write a c'tor?
    Do you not know how to use a c'tor to intialize an object?
    Do you not understand overloading?
    Do you not realize that overloading c'tors is for all intents and purposes identical to overloading methods?

  • Try blocks in overloaded constructors.

    I'm currently working on a program for my Data Structures class that will randomly generate lottery tickets for the user. I've designed a class to represent the tickets so that I can manipulate the data and such. I have one main constructor with 6 parameters and a few other overloaded constructors to provide default values when less than 6 arguments are provided in the call.
    Here's my problem: I think it would be cool to design a constructor that takes an int array as it's parameter with all the data contained in the array already. This seems like a great place to experiment with the try blocks so I can test that the array has enough values before the values are accessed. My current implementation of the try block conflicts with the semantics of using the "this" keyword in overloaded constructors: "this" must come first in the constructor. I'm not sure what to do, and since it's the first time I've ever even attempted to use try blocks, I don't have a clue what to ask...
    I have this ----------------------------------------->
    {noformat}{noformat}{noformat}public Ticket( int cap1, int low1, int high1, int cap2, int low2, int high2) {{noformat}{noformat} // Some initializations and method calls here{noformat}{noformat}}{noformat}{noformat}public Ticket( int ticketParams[] ) {{noformat}{noformat} try {{noformat}{noformat} this (ticketParams[0], ticketParams[1], ticketParams[2],{noformat}{noformat} ticketParams[3], ticketParams[4], ticketParams[5] );{noformat}{noformat} } catch(ArrayIndexOutOfBoundsException err) {{noformat}{noformat} System.out.println("Array argument does not contain enough data.");{noformat}{noformat} }{noformat}{noformat}}{noformat}
    ------------------------------------------------------------^
    Should I be trying to do this another way, or is this not possible -- or even sensible?

    Assert them on the caller side, not on the callee i.e. the consturctor.
    Anyway a try/catch for an ArrayIndexOutOfBoundsException is useless because the exception would throw a message similar to yours and it is fatal for the program run continuation.

  • Overloading constructor

    Hello
    I am having an adhoc problem with overloaded constructors:
    public class myFileRead {
    private int type;
    public myFileRead(File mp3, int nomenclature) {  //constructor 2
    type = nomenclature;
    myFileRead(File mp3);
    public myFileRead(File mp3) {  //constructor 1
    //code excised
    }All that I am tyring to do is set a member variable in constructor 2 and call constructor 1. My IDE is saying a missing ")" in constructor 2 call to constructor 1 at the parameter mp3. I have done this before. I have done a clean build. What am I missing here? Any enlightment welcomed.

    Hi Vanilla
    That was stupid about the type-ing the argument.
    However now it is demanding that the this(mp3) be
    e the first line. Yes. As Adeodatus mentioned. This is a requirement of the Java language.
    I dont see why. To ensure that all constructors complete before anything else happens, I guess. You probably rarely or never need to do something else first, and by knowing that you can't just invoke a constructor any old time, you eliminate one potential source of a lot of inconsistent or invalid or unpredicatable state.
    This is not
    extending any other object, except Object of course.Irrelevant.
    Are not all constructors equal? Yeah, I guess so. I don't see what that has to do with anything.
    Does this thereby
    y prevent the technique of using overloaded
    constructor to set a member value and then call some
    other constructor declaration?No. It just means that if you're going to call another c'tor, it must be the first thing that you do.

  • Can we use an overloaded constructor of a Java Bean with Session Tracking

    Hi Friends,
    If any one can solve my query.... It would be helpful.
    Query:
    I have a Java Bean with an overloaded constructor in it. I want to use the overloaded constructor in my JSP.
    1. One way of doing that is to use it directly in the "Scriptlets" (<% %>). But then I am not sure of the way to do session tracking. I think I can use the implicit objects like "session", "request" etc. but not sure of the approach or of the implementation method.
    2. Another way is through the directive <jsp: useBean>. But I cannot call an overloaded constructor with <jsp: useBean>. The only alternative way is to use the directive <jsp: useBean> where I have to write getter and setter methods in the Java Bean and use the <jsp: setProperty> and <jsp: getProperty> standard actions. Then with this approach I cannot use the overloaded constructor.
    Can any one suggest me the best approach to solve this problem ?
    Thanks and Regards,
    Gaive.

    My first reaction is that you can refactor your overloaded constructor into an init(arguments...) method. Instead of overloaded constructor, you can call that init method. This is the ideal solution if possible.
    As to the two choices you listed:
    1. This is OK, I believe. You can use scriplet to define the bean and put it into session scope of the pageContext. I am not sure exactly what you meant by session tracking; whatever you meant, it should be doable using HttpSessionAttributeListener and/or HttpSessionBindingListener.
    2. Agreed. There is no way that <jsp:useBean> can call a constructor that has non-empty arguments.
    Please tell me how it works for you.

  • Overloading constructor of a child that inherits from a class that inherits from Windows.Forms

    The title might be a bit confusing so here is the layout.
    - classHForm inherits System.Windows.Forms.Form
    - frmDoStuff inherits classHForm  (written by someone else and used in several applications)
      - does not have a constructor specifically defined, so I added the following thinking it would override the parent
    Sub Public New()
    End Sub
    Sub Public New(byval data as string)
    'do stuff
    End Sub
    In my code, I want to instantiate frmDoStuff, but I need to overload it's constructor and populate fields within this form. The problem I'm running into is that when I run this, it is using the constructor from classHForm and ignores any constructor in frmDoStuff.
    I guess you can't override the parent constructor? Is that why it won't work?
    I didn't want to overload the classHForm constructor, but I will if that's the way to go.
    my code:
    dim frm as new frmDoStuff(myString)
    Note: I would love to show actual code, but not allowed. Against company rules.

    Your code is similar. The value I pass into frmDoStuff is supposed to set a value for a textfield.
    Public Class frmDoStuff
    Inherits classHForm
    Public Sub New(ByVal s As String, ByVal gridData() as String)
    txtMyTextField.text = s LoadGrid(gridData)
    End Sub
    I also have a datagridview I need to populate in frmDoStuff and thought I would have another string or string array as a second parameter to the constructor and then call a routine from the constructor to populate the datagrid.
    of course, when I run it this way, the code is not being reached. I'll build an example as COR suggested and maybe someone will see where I'm going wrong.
    [UPDATE]
    I created a simple example and it worked. So, now I need to try to understand what is different in the actual code.
    Here is my example:
    Parent Class inherits form
    Imports System.Windows.Forms
    Public Class classMyForm
    Inherits System.Windows.Forms.Form
    Sub New()
    ' This call is required by the designer.
    InitializeComponent()
    ' Add any initialization after the InitializeComponent() call.
    End Sub
    End Class
    Public Class frmDoStuff
    Inherits classMyForm
    Public Sub New()
    ' This call is required by the designer.
    InitializeComponent()
    ' Add any initialization after the InitializeComponent() call.
    End Sub
    Public Sub New(ByVal sStuff As String)
    MyBase.New()
    InitializeComponent()
    'Populate the textbox
    TextBox1.Text = sStuff
    End Sub
    End Class
    Public Class frmMyForm
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim frm As New frmDoStuff(TextBox1.Text)
    frm.Show()
    End Sub
    End Class
    Just to recap. The actual parent was created a few years ago and the child form that I'm calling, "frmDoStuff" was created a couple years back and is used in several applications. I need to use it in my application, but I need to populate a couple
    controls when the form is loaded. As you can see in this example, I successfully overloaded the constructor to populate the textbox in frmDoStuff.
    In my real life situation, my overloaded constructor seems to be getting ignored when i step through the code. I'll go back and do some more testing.

  • Confused bout concept of Overloading Constructor

    Hi all...
    hope someone can clear this doubt of mine...
    I'd thought that Java supports overloading constructors but why is it that when I created two constructors for a class, the editor is telling me things like unresolved symbols for the second constructor?
    Although both constructors takes in 4 parameters, they are actually of different type and I can't understand why it won't work..
    can someone please clarify this with me?
    Thanks in advance! :D

    Thanks
    //this is the constructor classes
    public class ConnectionList extends JPanel{
        public ConnectionList(ObjectPanel initOPanel, int lt, JFrame parentPanel)
            oPanel = initOPanel;
            listType = lt;
            parent = parentPanel;
            objectName = oPanel.getCurrentObjectName();
            objectType = oPanel.getCurrentObjectType();
        public ConnectionList(String OName, int OType, int lt, JFrame parentPanel)
         listType = lt;
         parent = parentPanel;
         objectName = OName;
         objectType = OType;
    //I call to the class constructors using these:
    //no problem for this one (first constructor):
    inputList = new ConnectionList(oPanel, inputType, parentPanel);
    //oPanel is the ObjectPanel object
    //parent Panel is JFrame
    //inputType is an integer
    //somehow this one gives the error of unresolved symbols (2nd constructor)
    checkList = new ConnectionList(objectN, objectT, 1, parentPanel);
    //objectN, objectT are all string objects
    //parentPanel is the JFrame object
    //and this...Thanks again!

  • Help with constructors, accessors and mutators

    Hi all...
    Can anyone give me a code for the following problem with the use of constructors, accessors and mutators ?
    Programme is :
    Create a class called Stock that has the following attributes:
    STKID : integer
    DESC : STRING
    COSTPRICE : float
    SALEPRICE : float
    QTY : integer
    Create constructors, accessors and mutators for the above class.
    Create an array of object that can store up to 100 of the above objects.
    Implement the following functionalities:
    Add new Stock Record
    Search Stock Record
    Delete Stock Record
    Update Stock Record
    Its quite urgent, since I got to submit this for my interview tomorrow. So if anyone knows the code please do reply. Thanks in advance.
    Thanks and Regards,
    Jayanth.

    @jayanth: Ignore these guys - they're just sour and don't understand the value of helping each other out. Besides, I'm bored, and this was an easy write-up. I can send the code to your email ([email protected]) if you'd like. Just let me know.

  • Gettin "Assertion Failed" message and "Assert: parent node must have _DOMElement set", first when trying to bookmark and then when the "auto fill" on some web sites is used. Started after 3.6.9 automatic upgrade.

    Open Firefox and navigate to web site. Try to save to bookmarks and get the "assertion Failed" message and "Assert: parent node must have _DOMElement set" followed by a list of 8 (0-8) items.

    Try the Tiny Menu extension. I am using an older version of Tiny Menu on Lucid with Firefox 3.6.x and it works fine.

  • I removed chrome 10 and newly installed FF4 final, and I can't read PDF files within the browser. There was no problem in Chrome.

    I removed chrome 10 and newly installed FF4 final, and I can't read PDF files within the browser. There was no problem in Chrome. I can't even see the acrobat reader plugin in the plugins page. Acrobat 10 is already installed in my PC. Every time I try to read a PDF file on the web, FF tries to download it instead.

    As recommended above by Bernd Alheit, I posted this on the Adobe Reader forum. There, I received the advice to repair the installation under the help menu, which I did and it fixed the problem.
    Similar to your solution but found it's a fix found under "HELP" menu and not Add/Remove.
    Thank you.

  • In IMovie my project view is fine until it is finalized and then images are getting partially cut off on top(people's heads etc) Is there something I can do?

    In IMovie my project view is fine until it is finalized and then images are getting partially cut off on top(people's heads etc) Is there something I can do?

    My issue turned out possibly being a larger problem. 
    All of a sudden the server is in a bad, bad way.  30 minutes to get booted to the login screen.  If I try to login I get beachballs for half a second at a time.  I type login/password, the screen refreshes and I'm back to the login screen.  I can't connect a keyboard/mouse directly to it, because it wants to do the keyboard recognition (I'm not using an Apple keyboard because they're all Bluetooth and I can't get in to do the Bluetooth sync).  I can't do Disk Utility, because I can't connect a keyboard to do the key shortcut.  I can't do Hardware Test, because I can't connect a keyboard to do the key shortcut.  Can't reinstall Snow Leopard Server, because in their infinite wisdom Apple has removed the optical drive, and even if I had the optical, it wouldn't do any good because I can't connect a keyboard to do the key shortcut that would allow me to boot from the DVD.
    I tried to do target disk override from Remote Desktop but it won't let me choose my other Mac's Remote Disc as a boot option.  It also continues to show the Server as "Offline" even though power is on and it's on the network.
    I would do my 2010 Air's USB drive - just to do a Disk Utility and see if it's a drive problem - but I can't tell the Server to boot from the USB stick.
    Tried using my iMac as a monitor, that worked for a while, now it just flashes and then goes back to the iMac.
    I'm thinking the logic board on this thing is about to die.  Which is unfortunate, since my company opted out of AppleCare for this piece of equipment, and the 1 year expired last month.  So...if the repair is going to end up being $800, they're going to have to pony up for a new server.

  • Overloading constructor question

    The following douse not seem to work:-
    class A {
         A( int i ) {
              System.out.println( "A constructor" + i );
    class B {
         B( int i ) {
              System.out.println( "B constructor" + i );
    class C extends A {
         C () { // line 17
              System.out.println( "C constructor" );
         public static void main( String[] args ) {
              C c = new C();
    It complaines at line 17
    A(int) in A cannot be applied to ()
    C () {
    ^
    This has totaly bafeld be. I thought it was OK to add overloaded constructors in inheratid classes but it seems to be complaining that I am replacing C(int) wit C(), i.e. the constructor in the subclass has diferent arguments. surly this should simply add an overloaded constructer?
    Ben

    The first statement in every constructor must be a call to either a) another constructor in that class or b) a constructor of the super class. If you do not specify a call to either, then the compiler automatically will insert a call to the no argument constructor of the super class. Since there isn't a no-arg constructor in A, the compiler complains that you are calling the A(int) constructor with no arguments. You need to either add a no argument constructor to A, or you need to call the A(int) constructor from the C constructor with some default value.
    In case you didn't know, to call a super constructor from a subclass, you use the super keyword.
    Example:
    class A {
        A(int i) {}
    class B extends A {
        B() {
            super(2);  //This call the A(int) constructor.
    }

  • My trackpad is not final and the pointer jumps around the screen

    my trackpad is not final and the pointer jumps around the screen I wonder if physical or software problems
    my macbook pro is 13 mid 2012 model: MacBookPro9, 2
    so mountan lion
    About a week ago I have this problem and I worry as much care and not my mac n golpiad never fallen so surprise me either physical appreciate your response as soon as possible

    this happened to me and what i did was let it go flat and then charge it and it worked. i dont know if this will help but this is what i did when my phone went black.

  • Just updated to Imovie 11 created first video finalized and its gone!

    Just updated to Imovie 11 created first video finalized and its gone! The only file that remains anywhere on the computer is a .rcproject file that wont open in anything including Imovie. There is no record of the file anywhere in Imovie...Help!!! This was my final for a Music class and Im obviously screwed if I dont get this back...THANKS!

    When you finalize a movie, it places finished movies of all available sizes in the Media Browser. It is important to leave the rcproject file where it is in the Movies/iMovie Projects folder. If you have moved it, move it back.
    In iMovie, when you Share to iTunes, or Share to YouTube, etc. ti will use the Media Browser copy so it does not have to re-render. But if you do not Finalize first, no problem, you can still use all those options and cause a render.
    The Media Browser files are contained in the RCPROJECT package. Right click on the rcproject file in the Movies/iMovie Projects folder for your project. Select SHOW PACKAGE CONTENTS. Like in the Movies folder, and you will see your movies.

  • [svn:bz-trunk] 17133: this time finally (and hopefully) adding all the flex-messaging-opt tomcat/jrun/oracle/weblogic/ websphere servers maven pom files in the right svn folder.

    Revision: 17133
    Revision: 17133
    Author:   [email protected]
    Date:     2010-07-30 02:01:44 -0700 (Fri, 30 Jul 2010)
    Log Message:
    this time finally (and hopefully) adding all the flex-messaging-opt tomcat/jrun/oracle/weblogic/websphere servers maven pom files in the right svn folder.
    Added Paths:
        blazeds/trunk/modules/opt/poms/oracle/
        blazeds/trunk/modules/opt/poms/oracle/pom.xml
        blazeds/trunk/modules/opt/poms/tomcat4/
        blazeds/trunk/modules/opt/poms/tomcat4/pom.xml
        blazeds/trunk/modules/opt/poms/tomcat6/
        blazeds/trunk/modules/opt/poms/tomcat6/pom.xml
        blazeds/trunk/modules/opt/poms/weblogic/
        blazeds/trunk/modules/opt/poms/weblogic/pom.xml
        blazeds/trunk/modules/opt/poms/websphere/
        blazeds/trunk/modules/opt/poms/websphere/pom.xml

Maybe you are looking for

  • Is there a way to speed up charts on Forms?

    Hi, I have a chart incorporated on a form using the chart wizard. The problem is that the first chart generated takes forever although subsequent charts are seem much faster. I know that this is related to Oracle Graphics Batch but is there a way to

  • To copy a site from the net to edit.

    i have been asked to edit someones website, and i am having trouble gaining the information i need to download the site into dreamweaver to work on. what info do i need specifically for the ftp server, etc? sorry for being so daft in this. even if so

  • Why is the extra icloud storage I purchased a month ago, not showing in icloud?

    Why is the extra icloud storage I purchased a month ago, not showing in cloud? I created a new apple id @icloud thinking that my regular email address wasn't acceptable for icloud but the 10 gigs I purchased are still not showing up, nor are any of t

  • Upload times out

    Hi Thanks in advance for your help I am trying to upload a csv file (about 5000 rows and 30 columns ) into a database table by using the Upload tool. I can see the data in APEX with the mapping but when when I hit "load data", it takes like 2 minutes

  • My latest itunes version is disabling me from turning manual sync on, on my apple devices. how can i prevent this?

    everytime i connect my iphone on my laptop my itunes keeps on turning off the manual sync for songs. everytime i turn it on it erases all the contents, but when i reconnect it it's off again. how can i fix this?