Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java Multiple Constructors Question

  1. Dec 24, 2013 #1
    In the main activity, I call one of the constructors:

    public Something()
    {
    //nothing initalized
    }


    public Something(7 variables)
    {
    ... (this.variable = variable)
    }


    public Something(10 variables)
    {
    ... (this.variable = variable)
    }


    I call the 7 variable one but the program won't run and I think its because of overloading. I read that we're suppose to set the first constructor to this(variable, variable, variable, etc); But an error occurs saying the global variables have to be static and when I do change them to static the other two constructors (the ones initialized) says error that the variables can't be static. Is there a better way to handle multiple constructors?
     
  2. jcsd
  3. Dec 24, 2013 #2

    AlephZero

    User Avatar
    Science Advisor
    Homework Helper

    There's a better way to ask your question, and that is to show ALL the relevant code, not just some pseudocode with a vague description of what "you think" and what "you have read".

    I would take a guess that your "global variables that have to be static" should not be global variables at all, but that's just a guess.

    This might help. http://www.brpreiss.com/books/opus5/html/page596.html
     
  4. Dec 24, 2013 #3

    jedishrfu

    Staff: Mentor

    The best way to write these constructors is to have the empty constructor and the 7-arg constructor call the 10-arg constructor to do the initialization via the this reference that way all initializations essentially done in one place.

    With respect to static variables in the class, you should be able to assign a value to them in your constructor without a problem.

    Sometimes people use a counter static variable that get incremented each time an instance is created ie the constructor is called.

    As AlephZero has said you really need to show some concrete listing using the [ code ] tags so we can see where your issue lies.
     
  5. Dec 26, 2013 #4
    I'm sorry. Here's the code:

    I call it in the Main class
    Code (Text):
    note = new Note(9, "Calendar", "Day", date, sTime, eTime, list);
    Code (Text):

    static int id;
    static String name;
    static String description;
    static Date date;
    static Time sTime;
    static Time eTime;
    private static List list;
    Boolean flag;
    int sid;
    private int bid;
    String notes;

    public Note()
        {
            this(id, name, description, date, sTime, eTime, list);
        }
       
    public Note(int id, String name, String description, Date date, Time sTime, Time eTime, List list)
        {
            this.id = id;
            this.name = name;
            this.description = description;
            this.date = date;
            this.sTime = sTime;
            this.eTime = eTime;
            this.setList(list);
        }  
       
    public Note(int id, String name, String description, Date date, Time sTime, Time eTime, Boolean flag, int sid, int bid, String notes)
        {
            this.id = id;
            this.name = name;
            this.description = description;
            this.date = date;
            this.sTime = sTime;
            this.eTime = eTime;
            this.setList(list);
            this.flag = flag;
            this.sid = sid;
            this.setBid(bid);
            this.notes = notes;
           
        }  
     
    By changing the global variables to static, a warning occurs in the last two constructors "The static field Note.id should be accessed in a static way."
     
  6. Dec 26, 2013 #5

    jedishrfu

    Staff: Mentor

    Okay I see the problem, when using the this. and the variables are static the compiler is warning you that there may be a problem.

    Specifically using the this.name means that name is not a static variable (aka a class variable). So everytime someone uses your constructor they will change the name variable for every other instance you've already constructed and that doesn't seem like what you want.

    If you do want to change a static then simply reference it by its name without the this. prefix. However in your case you can't do that either because your argument name and class vairable share the same name.

    You have the following choices:
    - use the Note.name = name; in your constructor
    - change the name of your argument to avoid the conflict: name = _name;
    - change the name of your static name to avoid the conflict: _name=name
    - don't change statics via your constructor (best practice to follow)
    - use a factory class to create the Note instance you want:

    newnote = NoteFactory.createDescriptiveNote(.....9 args.....);
    newnote = NoteFactory.createBriefNote(...7 args...);
    newnote = NoteFactory.createBlankNote(...no args...);
     
  7. Dec 26, 2013 #6
    I think the problem is that you don't understand what static actually does to your code. When using static only one instance of a static field exists. I am unsure of exactly what you are trying to accomplish with your code, other then what the class does, but I would say its probably best to not have all these declared as statics:
    Code (Text):
    static int id;
    static String name;
    static String description;
    static Date date;
    static Time sTime;
    static Time eTime;
    private static List list;
     
  8. Dec 26, 2013 #7
    Oh I see. If I don't want my variables to be static, what should I do to the first constructor (to avoid overloading)?
     
  9. Dec 26, 2013 #8
    Consider the code you provided:
    Code (Text):

    public Note()
    {
      // These are arguments, are currently undefined.
      this(id, name, description, date, sTime, eTime, list);
    }
     
    How is this code going to call the other constructor namely:
    Code (Text):

    public Note(int, String, String, Date, Time, Time, List )
     
    If you have not yet defined what id, name, description, date, stime, etime, and list are ?

    The compiler has no idea what you are doing perhaps you could use a default value for these arguments rather then passing in undefined objects.

    Also what is wrong with not just doing this for the default constructor:
    Code (Text):

    public Note() { }
     
    Then have your overloaded constructors below it?

    Basically, overloading means that the same method name can be defined with more than one signature — the list of formal parameters (and their types).

    So for example, you could have a default constructor Note() that does nothing but creates the object. Then a overloaded constructor that contains different types of arguments Note(...7 arguments...), Note(...11 arguments...) whatever you want. Each constructor will create the object, the only difference is that you can pass different parameters to them using one versus the other.
     
    Last edited: Dec 26, 2013
  10. Dec 26, 2013 #9

    AlephZero

    User Avatar
    Science Advisor
    Homework Helper

    Usually, you want to call this(........) with constants that are the default values for the data, for example this(0, "no name", "no description", ... etc , ...)

    For example in the link I gave in my earlier post, the "no argument" constructor for the complex number sets the real and imaginary parts to 0, rather than leaving them uninitialized.

    It's much cleaner to have all the object's data fields initialized to some value, otherwise you will tie yourself in knots both when you try to write the other methods for the class, and when you try to use the class.
     
    Last edited: Dec 26, 2013
  11. Dec 28, 2013 #10
    Oh I got it! In the beginning, I thought the error in my program had to do with multiple constructors but it wasn't the case.

    But to clarify some of the things mentioned here:
    If I just left it as an empty constructor isn't that the same as not having that constructor at all because it doesn't do anything? (how does it create the object if nothing is initialized?)
     
  12. Dec 28, 2013 #11
    It initializes the object, but does not set the internal members to anything. You could add setter functions to set them to specific values. I am pretty sure you don't need a default constructor, if you don't want one.

    I believe a default constructor will only be automatically generated by the compiler if no other constructors are defined. But since you already have more then one its not necessary.
     
  13. Dec 30, 2013 #12
    Got it! Thank You everyone!!! :smile:
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Java Multiple Constructors Question
  1. Java Question (Replies: 2)

  2. Java question (Replies: 5)

  3. Java Question (Replies: 2)

  4. Java Question (Replies: 3)

Loading...