Calling constructor from another constructor and illegal argument exception - java

for my two parameter constructor to call the four parameter constructor is it proper with what I have done(I am still learning). Also it is supposed to instantiate open interval so is that still correct? for the copy constructor how would I make a copy of the explicit value constructor? Also how do I throw an exception if memory has not been allocated for object being copied?

for the copy constructor how would I make a copy of the explicit value constructor?
There is no built-in in Java for this. You'd have to manually copy the fields you want to copy
public LetsCallThisClassInterval(LetsCallThisClassInterval other){
this(other.left, other.right, other.stuff)
}
But this class looks like it should be immutable, so there is no real need for a copy constructor.
Also how do I throw an exception if memory has not been allocated for object being copied?
That just does not happen in Java. Memory is managed for you, and if you get an object reference, it will have been properly allocated already.
Or are you talking about other being null in the above example?
In that case, you will get a NullPointerException automatically. If you prefer an IllegalArgumentException (debatable), you can add a null check:
if (other == null)
throw new IllegalArgumentException("other interval cannot be null");

Let me see if I get this right, you want to do a constructor inception? In this case what you would want to do is use the Constructor(//insert the variables that correspond); that should fix the problem.
Using "this" will make the constructor refer to itself, I mean the same method. For example it would be.
public Constructor(char leftsym, double left, double right, char rightsymb){
new Constructor(left, right);
}
Now as a side note, the Constructor class already exists between the core classes in Java, I suggest that if you want to simplify your life change your java class name such as Constructor_1 or something like that.
Good Luck

Related

Java - should I use new() in Setters or not?

I see that a default setX function just uses X = _x, but in Java wouldn't it be just a reference to the _x object?
Shouldn't I use X = new X(_x) instead?
I truly looked for an answer, and haven't found one.
To be semantically correct, _x isn't an object, it's a parameter, and it's referring to an object. And yes, afterwards your X will be a copy of that reference, so it will point to the same object.
But usually that is exactly what you want to achieve. You don't want to spawn new objects whenever you set a value. And often you explicitly want it to be exactly the same object.
It's only if the calling site considers its version of the object as private property, that it's its responsability to produce and set a copy instead.
The name setter implies: setting a field.
That method isn't called storeCopyOf(), is it?
Of course you can use new (in case the corresponding class offers a copy constructor), but doing so in a setter is not common practice. And as shown, doing so is very misleading given the meaning that the name setX() communicates.
Shouldn't I use X = new X(_x) instead?
No, you shouldn't. A user of your API expects to set exactly the given instance, not a copy of it.
You could validate this incoming instance by throwing an exception if it doesn't fit your needs, but it's really unclear to set a copy.
Probably, you may want to return a value from a getter by using this approach. Returning a copy of an inner field (of a reference type) is a good technique to maintain immutability.
We use setter (and getter) method to implement encapsulation.
Example :
private String myField; //"private" means access to this is restricted
public String getMyField()
{
//include validation, logic, logging or whatever you like here
return this.myField;
}
public void setMyField(String value)
{
//include more logic
this.myField = value;
}
Someone who is using your APIs, will pass these value according to need, like :
obj.setMyField("myvalue");
If x is a primitive type, then there is no need to recreate the value with a copy constructor as changes to its value elsewhere won't affect the local copy.
If you are setting a mutable (changeable) object, but you don't want your copy changed, then yes you should use a copy constructor in your setter. However I'd hesitate to call that setting, it's more like a saveCopy(_x);

Making a new Object in java [duplicate]

This question already has answers here:
Should I instantiate instance variables on declaration or in the constructor?
(15 answers)
Closed 9 years ago.
When I use Java based on my C++ knowledge, I love to initialize variable using the following way.
public class ME {
private int i;
public ME() {
this.i = 100;
}
}
After some time, I change the habit to
public class ME {
private int i = 100;
public ME() {
}
}
I came across others source code, some are using 1st convention, others are using 2nd convention.
May I know which convention do you all recommend, and why?
I find the second style (declaration + initialization in one go) superior. Reasons:
It makes it clear at a glance how the variable is initialized. Typically, when reading a program and coming across a variable, you'll first go to its declaration (often automatic in IDEs). With style 2, you see the default value right away. With style 1, you need to look at the constructor as well.
If you have more than one constructor, you don't have to repeat the initializations (and you cannot forget them).
Of course, if the initialization value is different in different constructors (or even calculated in the constructor), you must do it in the constructor.
I have the practice (habit) of almost always initializing in the contructor for two reasons, one in my opinion it adds to readablitiy (cleaner), and two there is more logic control in the constructor than in one line. Even if initially the instance variable doesn't require logic, having it in the constructor gives more flexibility to add logic in the future if needed.
As to the concern mentioned above about multiple constructors, that's easily solved by having one no-arg constructor that initializes all the instance variables that are initilized the same for all constructors and then each constructor calls this() at the first line. That solves your reduncancy issues.
I tend to use the second one to avoid a complicated constructor (or a useless one), also I don't really consider this as an initialization (even if it is an initialization), but more like giving a default value.
For example in your second snippet, you can remove the constructor and have a clearer code.
If you initialize in the top or in constructor it doesn't make much difference .But in some case initializing in constructor makes sense.
class String
{
char[] arr/*=char [20]*/; //Here initializing char[] over here will not make sense.
String()
{
this.arr=new char[0];
}
String(char[] arr)
{
this.arr=arr;
}
}
So depending on the situation sometime you will have to initialize in the top and sometimes in a constructor.
FYI other option's for initialization without using a constructor :
class Foo
{
int i;
static int k;
//instance initializer block
{
//run's every time a new object is created
i=20;
}
//static initializer block
static{
//run's only one time when the class is loaded
k=18;
}
}
The only problem I see with the first method is if you are planning to add more constructors. Then you will be repeating code and maintainability would suffer.
I recommend initializing variables in constructors. That's why they exist: to ensure your objects are constructed (initialized) properly.
Either way will work, and it's a matter of style, but I prefer constructors for member initialization.
Both the options can be correct depending on your situation.
A very simple example would be: If you have multiple constructors all of which initialize the variable the same way(int x=2 for each one of them). It makes sense to initialize the variable at declaration to avoid redundancy.
It also makes sense to consider final variables in such a situation. If you know what value a final variable will have at declaration, it makes sense to initialize it outside the constructors. However, if you want the users of your class to initialize the final variable through a constructor, delay the initialization until the constructor.
One thing, regardless of how you initialize the field, use of the final qualifier, if possible, will ensure the visibility of the field's value in a multi-threaded environment.
I think both are correct programming wise,
But i think your first option is more correct in an object oriented way, because in the constructor is when the object is created, and it is when the variable should initialized.
I think it is the "by the book" convention, but it is open for discussion.
Wikipedia
It can depend on what your are initialising, for example you cannot just use field initialisation if a checked exception is involved. For example, the following:
public class Foo {
FileInputStream fis = new FileInputStream("/tmp"); // throws FileNotFoundException
}
Will cause a compile-time error unless you also include a constructor declaring that checked exception, or extend a superclass which does, e.g.:
public Foo() throws FileNotFoundException {}
I would say, it depends on the default. For example
public Bar
{
ArrayList<Foo> foos;
}
I would make a new ArrayList outside of the constructor, if I always assume foos can not be null. If Bar is a valid object, not caring if foos is null or not, I would put it in the constructor.
You might disagree and say that it's the constructors job to put the object in a valid state. However, if clearly all the constructors should do exactly the same thing(initialize foos), why duplicate that code?

How to handle cases where allocated object is never used

In some cases, the constructor call is everything needed, and I do not need any method invocation on the created object. Depending on Java-Compiler-Preferences, Eclipse gives a warning/error "The allocated object is never used" if I do not assign the created object to a variable, or a warning/error "The value of the local variable is not used" if I assign it to a variable.
I know that I can turn off the warnings/errors in the Eclipse Preferences. My question is: For which reason does Eclipse report "The allocated object is never used"? And if there are good reasons, how should I handle these cases, where no method invocation on the created object is needed?
If all your class's logic is executed in the constructor, perhaps you should move it to a static method instead of creating an instance you'll never use.
A constructor is meant to create an instance of a class to be used later. I think you might be misusing the constructor.
From Eclipse specs this,
When enabled, the compiler will issue an error or a warning when it encounters an allocated object which is not used, e.g.
if (name == null)
new IllegalArgumentException();
But it reports as a bug. Just ignore it no need.

Instantiate objects in initialization?

I have a class that holds another objects inside it (List, Set and objects from my application).
public class SomeClass {
private List l;
private SomeObject obj;
//...
}
Is a good practice instantiate these objects where the SomeClass object is created to avoid NullPointerException? Something like:
public class SomeClass{
private List l = new ArrayList();
private SomeObject obj = new SomeObject();
//...
}
In a normal way, these objects will be generated in some processing/analysis, but errors can occur and the objects still with null value.
Yes, it is a good practice to do so. The constructor is a natural place to instantiate member objects. You can also create them right where they are declared:
private List l = new ArrayList();
However, it might be a good idea to restructure or modify your code so that NullPointerExceptions won't occur, regardless of the order in which the methods are called.
If an empty List or a default object of that class is a valid state in every following operation, yes, instantiate a default. However, if the default would be an invalid state, don't do it.
Well I prefer to initialize because sometimes is a headache to find where's the null pointer exception, and if u initialize your objects with constructors the object inside should be initialized.
Hope this help you.
It's generally good practice to instantiate member fields (whether objects or primitives) at creation time whenever the default value (0, false, or null) is not what you want. One time to defer this is for lazy instantiation. (This is used, for instance, when an object might not be needed after all and creating it is expensive.) Another time to defer this is when other initialization needs to take place beforehand.
Assuming you want to initialize a field at object creation time, there are two ways to do it: with an initializer expression as you showed or in the constructor(s). There isn't too much difference, other than that instance initializers run before the first line of the constructor. This may or may not cause problems, depending on your code logic.
It's also a good idea to declare member fields final whenever they are initialized at object creation and are expected to not change during the life of the object. A side benefit of declaring a field final is that the compiler will catch any failure to initialize it. (The compiler requires definite assignment to consider a final field to be properly initialized.)
You are talking about eager construction versus lazy construction. There are places where each has value.
In many situations, it is better to lazily create things as it saves memory. But then you must check for null every time you try to get data
In some situations, it makes sense to create the object upfront, either to avoid the null checking mentioned above or to avoid the object creation time hit during an intensive process
It is normal to generate them like this, but it's not a nice way to code to generate them just to avoid NPE. There should be proper validation in code, rather than assigning garbage-eligible objects which won't be utilized.
You can also assign some default states - like Collections.emptyList(), or
in a constants class:
DEFAULT_STATE = new SomeState();
then simply
class A {
State obj = Constants.DEFAULT_STATE;
}

Should I initialize variable within constructor or outside constructor [duplicate]

This question already has answers here:
Should I instantiate instance variables on declaration or in the constructor?
(15 answers)
Closed 9 years ago.
When I use Java based on my C++ knowledge, I love to initialize variable using the following way.
public class ME {
private int i;
public ME() {
this.i = 100;
}
}
After some time, I change the habit to
public class ME {
private int i = 100;
public ME() {
}
}
I came across others source code, some are using 1st convention, others are using 2nd convention.
May I know which convention do you all recommend, and why?
I find the second style (declaration + initialization in one go) superior. Reasons:
It makes it clear at a glance how the variable is initialized. Typically, when reading a program and coming across a variable, you'll first go to its declaration (often automatic in IDEs). With style 2, you see the default value right away. With style 1, you need to look at the constructor as well.
If you have more than one constructor, you don't have to repeat the initializations (and you cannot forget them).
Of course, if the initialization value is different in different constructors (or even calculated in the constructor), you must do it in the constructor.
I have the practice (habit) of almost always initializing in the contructor for two reasons, one in my opinion it adds to readablitiy (cleaner), and two there is more logic control in the constructor than in one line. Even if initially the instance variable doesn't require logic, having it in the constructor gives more flexibility to add logic in the future if needed.
As to the concern mentioned above about multiple constructors, that's easily solved by having one no-arg constructor that initializes all the instance variables that are initilized the same for all constructors and then each constructor calls this() at the first line. That solves your reduncancy issues.
I tend to use the second one to avoid a complicated constructor (or a useless one), also I don't really consider this as an initialization (even if it is an initialization), but more like giving a default value.
For example in your second snippet, you can remove the constructor and have a clearer code.
If you initialize in the top or in constructor it doesn't make much difference .But in some case initializing in constructor makes sense.
class String
{
char[] arr/*=char [20]*/; //Here initializing char[] over here will not make sense.
String()
{
this.arr=new char[0];
}
String(char[] arr)
{
this.arr=arr;
}
}
So depending on the situation sometime you will have to initialize in the top and sometimes in a constructor.
FYI other option's for initialization without using a constructor :
class Foo
{
int i;
static int k;
//instance initializer block
{
//run's every time a new object is created
i=20;
}
//static initializer block
static{
//run's only one time when the class is loaded
k=18;
}
}
The only problem I see with the first method is if you are planning to add more constructors. Then you will be repeating code and maintainability would suffer.
I recommend initializing variables in constructors. That's why they exist: to ensure your objects are constructed (initialized) properly.
Either way will work, and it's a matter of style, but I prefer constructors for member initialization.
Both the options can be correct depending on your situation.
A very simple example would be: If you have multiple constructors all of which initialize the variable the same way(int x=2 for each one of them). It makes sense to initialize the variable at declaration to avoid redundancy.
It also makes sense to consider final variables in such a situation. If you know what value a final variable will have at declaration, it makes sense to initialize it outside the constructors. However, if you want the users of your class to initialize the final variable through a constructor, delay the initialization until the constructor.
One thing, regardless of how you initialize the field, use of the final qualifier, if possible, will ensure the visibility of the field's value in a multi-threaded environment.
I think both are correct programming wise,
But i think your first option is more correct in an object oriented way, because in the constructor is when the object is created, and it is when the variable should initialized.
I think it is the "by the book" convention, but it is open for discussion.
Wikipedia
It can depend on what your are initialising, for example you cannot just use field initialisation if a checked exception is involved. For example, the following:
public class Foo {
FileInputStream fis = new FileInputStream("/tmp"); // throws FileNotFoundException
}
Will cause a compile-time error unless you also include a constructor declaring that checked exception, or extend a superclass which does, e.g.:
public Foo() throws FileNotFoundException {}
I would say, it depends on the default. For example
public Bar
{
ArrayList<Foo> foos;
}
I would make a new ArrayList outside of the constructor, if I always assume foos can not be null. If Bar is a valid object, not caring if foos is null or not, I would put it in the constructor.
You might disagree and say that it's the constructors job to put the object in a valid state. However, if clearly all the constructors should do exactly the same thing(initialize foos), why duplicate that code?

Categories