Java Multiple Constructors Question

In summary: and avoids some problems that can arise if you try to use the this(...) constructor with uninitialized values.
  • #1
whitehorsey
192
0
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?
 
Technology news on Phys.org
  • #2
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
 
  • #3
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.
 
  • #4
I'm sorry. Here's the code:

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

Code:
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."
 
  • #5
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...);
 
  • #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:
static int id; 
static String name; 
static String description; 
static Date date;
static Time sTime; 
static Time eTime; 
private static List list;
 
  • #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)?
 
  • #8
whitehorsey said:
Oh I see. If I don't want my variables to be static, what should I do to the first constructor (to avoid overloading)?

Consider the code you provided:
Code:
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:
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:
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:
  • #9
whitehorsey said:
Oh I see. If I don't want my variables to be static, what should I do to the first constructor (to avoid overloading)?

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:
  • #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?)
 
  • #11
whitehorsey said:
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?)

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.
 
  • #12
MathWarrior said:
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.

Got it! Thank You everyone! :smile:
 

FAQ: Java Multiple Constructors Question

1. What is the purpose of having multiple constructors in Java?

Multiple constructors allow for the creation of objects with different initial states or configurations. This provides flexibility in how objects are created and allows for more efficient coding by avoiding the need for multiple lines of code to set different initial values.

2. How do you declare multiple constructors in Java?

To declare multiple constructors, you must use the same name for each constructor, but with different parameters. This allows the compiler to differentiate between the constructors and call the appropriate one based on the arguments passed in.

3. Can a class have both default and parameterized constructors in Java?

Yes, a class can have both default and parameterized constructors. The default constructor is the one that is automatically created by the compiler if no other constructors are declared. A parameterized constructor, on the other hand, allows for the initialization of objects with specific values.

4. How do you call one constructor from another in Java?

To call one constructor from another, you can use the keyword "this". For example, "this(parameters)" can be used in the body of a constructor to call another constructor with the specified parameters. This must be the first line in the constructor's body.

5. Is it possible to have a private constructor in Java?

Yes, it is possible to have a private constructor in Java. A private constructor can only be accessed within the same class, and is typically used for creating utility classes that do not need to be instantiated or for implementing singleton design patterns.

Similar threads

Replies
36
Views
2K
Replies
36
Views
2K
Replies
13
Views
1K
Replies
18
Views
8K
Replies
89
Views
5K
Replies
23
Views
2K
Replies
26
Views
3K
Replies
4
Views
2K
Back
Top