Java Multiple Constructors Question

  • Context: Java 
  • Thread starter Thread starter whitehorsey
  • Start date Start date
  • Tags Tags
    Java Multiple
Click For Summary
SUMMARY

The discussion centers on the implementation of multiple constructors in Java, specifically regarding the handling of static and instance variables. The user encountered issues when attempting to call a constructor with seven parameters from an empty constructor, leading to confusion about static variable usage. The recommended solution is to have the empty constructor call the more complex constructor with default values, ensuring proper initialization without relying on static variables. Best practices suggest avoiding static variables for instance-specific data to prevent unintended side effects.

PREREQUISITES
  • Understanding of Java constructors and overloading
  • Knowledge of static vs. instance variables in Java
  • Familiarity with Java data types such as String, Date, and Time
  • Basic grasp of object-oriented programming principles
NEXT STEPS
  • Learn about Java constructor overloading techniques
  • Explore best practices for using static and instance variables in Java
  • Research Java factory design patterns for object creation
  • Study Java's default constructor behavior and its implications
USEFUL FOR

Java developers, software engineers, and students learning object-oriented programming who want to deepen their understanding of constructor usage and variable management in Java.

whitehorsey
Messages
188
Reaction score
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
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
 
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.
 
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."
 
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...);
 
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;
 
Oh I see. If I don't want my variables to be static, what should I do to the first constructor (to avoid overloading)?
 
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:
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:
 

Similar threads

  • · Replies 36 ·
2
Replies
36
Views
3K
  • · Replies 36 ·
2
Replies
36
Views
3K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 13 ·
Replies
13
Views
1K
  • · Replies 18 ·
Replies
18
Views
9K
  • · Replies 23 ·
Replies
23
Views
3K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 26 ·
Replies
26
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 9 ·
Replies
9
Views
2K