Reputation: 458
class Target {
String name;
int amount;
double weight;
Target (String targetName, int targetAmount, double targetWeight) {
name = targetName;
amount = targetAmount;
weight = targetWeight;
}
}
A completely arbitrary constructor which is not part of something bigger.
Suppose I create an instance of this somewhere If I input the wrong type of argument
Target object1 = new Target("Apple", 4.32, "who knows?")
How can I make the constructor check if the type of argument is correct and if it isn't, ask to declare object1
again.
Is it acceptable to write while loops inside the constructor? (using instanceof
checks as long as the type is incorrect and ask to reinput)
Another idea is to create a separate method which deals with the instanceof
checks, but the arguments have different types, is there a way to return the declared type of the argument?
OR am I completely over-thinking this and there is an easier way to do this?
Upvotes: 0
Views: 1438
Reputation: 36304
Target object1 = new Target("Apple", 4.32, "who knows?")
will give you a compile time error. The method calls are resolved during compile time but the actual calls are done during runtime.
So, once it encounters the above statement, the compiler checks if a constructor which is capable of taking these arguments is present, if no, then you get an error.
How can I make the constructor check if the type of argument is correct and if it isn't, ask to declare object1 again. -
You shouldn't do it. A constructor is invoked when new is called
i.e when an object is being created, If the arguments don't match, then the constructor itself won't be called. Use a static helper method for this (if needed).
Is it acceptable to write while loops inside the constructor? (using instanceof checks as long as the type is incorrect and ask to reinput)
You should not have any business logic inside a constructor. That's all. instanceof
checks may be acceptable depending on context (case-to-case basis)
am I completely over-thinking this and there is an easier way to do this - YES. Don't call a constructor with invalid arguments. Don't put business logic in it. Validation logic is acceptable.
Upvotes: 1
Reputation: 578
Firstly, if you give wrong parameters to constructor, java compiler will return an error. Answering your second question it is acceptable to use while loop inside the constructor.
Upvotes: 2
Reputation: 3180
You don't need to, because Java compiler will already give you an error during compile-time. It is Strong typed, meaning that a variable will only have one type and ONE TYPE ONLY.
The code you gave will not compile
Upvotes: 3