I need to create an object of some type.
The class of the object has just one constructor (one that I've written).
My program receive requests to create instances of an objects with a parameter ID.
I want to stop the constructor if the ID parameter contains a char that is not a digit.
I cannot check the parameter before, since I'm not the one who calls the constructor.
Make the constructor private and expose a static factory method, that will validate and return a new instance of the object if the parameter is valid.
The only way to "stop" a constructor is to throw an exception. Bearing in mind of course that the caller is supposed to "know" about this exception and be able to handle the case where the constructor fails.
Throwing an exception from the constructor doesn't stop the object being created though, It just makes the assignment of its reference to a variable fail and the reference unavaliable (and therefore eligible for garbage collection) unless you make the mistake of passing this to an external method from the constructor itself. (Which you shouldn't do anyway.)
How to solve this depends on what you want to happen when an illegal character is given, which in turn depends on what object we're talking about, and how the consuming library is using it.
The most reasonable thing to do would be to throw an IllegalArgumentException, and this is what I'd suggest you do.
However, it might make sense to just return null, too, even though I'd strongly recommend against it (you can't do this directly in the constructor, but you can create a factory method that does this).
Related
I have a class which offers a public method that must only be called once.
What would be a proper exception to throw in case its called again?
My current candiate is RejectedExecutionException
IllegalStateException may be appropriate, or something similar. For example, calling Thread::start twice would throw IllegalThreadStateException.
I suggest something completely different:
Consider if you can change your design.
The fact that your interface allows to only call a method once puts a constraint on the users of your interface. Interfaces should make it easy to use them "the right way"; and make it hard to use them the wrong way.
So instead of thinking about the exception type to throw ... think about solutions to simply make it impossible to misuse the interface.
For example, make the method private - and invoke only within the constructor of some internal singleton object. That (more or less) guarantees that the method will be called exactly once.
I'm a die-hard C++ fan who is picking up Java for Android apps. In C++, the canonical way of creating and initializing an object would be to totally intialize it in the constructor:
class Message {
string payload;
int client;
// etc.
public:
Message(string payload, int client)
: payload(payload)
, client(client)
{}
};
This seems possible to do in Java. It gets a bit uglier because I want to make certain members const (the best Java can do is final), but generally I can figure it out.
But now I'm running across libraries such as FreeHEP-XDR, whose XDRSerializable interface specifies a signature:
void read(XDRDataInput in);
This function, which will be implemented by Message, is obviously not a static instantiator, as it returns void. The Message object would have to be fully constructed, probably with a default constructor, before calling this function. This bothers me: the caller can easily pass an XDRDataInput in the constructor, and anyway I'll be initializing the object twice (once in the default constructor, again in read). Most egregiously, implementing this requires me to drop my final modifier from certain Message data members, because they'll be modified after the constructor is finished!
Is this par for the course for Java? What's the object protection, creation, and initialization paradigm?
Well, the main issue with constructors is that they are not polymorphic. Meaning that the client whose invoking such constructors needs to always know what concrete type is she building. By deferring initialization and construction you can, pontentially, take the decision of which concrete instance you want to create at point a and polimorfically initialize it at point b.
Also, java does not have any way to force implementors of a certain contract (an interface, by example) to define a certain constructor. So it is either adding a weak condition to the interface contract (like a comment in the javadoc saying that implementors should provide a constructor that receives XHRDataInput) or adding a initialization method to the interface and forcing you to provide an empty constructor instead (which is by far a more common practice, probably inherited from the JavaBeans "specification").
Having said that I will also state: Yes it totally breaks your "final" semantics. You can add a check in your "read" method that checks over a certain condition and ensure that your object is initialized only once (throwing an Exception if read is invoked twice), but that is totally up to you.
I have few questions regarding Java constructors
Can a constructor be private? If yes then in which condition?
Is a constructor a method or not?
If a constructor does not return anything then why we are getting a new Object every time we call it?
What's the default access modifier of a constructor if we do not specify.
Edit
The answers for 1 & 3 are very clear. I'm still not sure about 2 & 4 since I'm getting different answers for them.
Can a constructor be private? If yes then in which condition?
Yes. There are no conditions. Of course, no one except the class itself can call it then.
This is actually a frequent pattern: Have a static getInstance() and keep the constructor private.
There can also be private constructors that the public constructors internally call.
Constructor is a method or not?
Hmm. I say "no". At the very least, it is a "very special kind of" method. In what context exactly? The terminology is less important than what you are trying to do.
If constructor does not return anything then why we are getting a new Object every time we call it.
The new operator returns something (the new instance).
Whats the default access modifier of a constructor.
Same as for methods. Package-private.
If you do not specify any constructor, the class gets a default constructor, which takes no arguments, does nothing except calling the parent constructor and is public.
Yes, in any case. However, if all constructors for a class are private, that means that the class cannot be directly instantiated. You will need to use something like the Factory Pattern to create instances of the object.
Yes, the constructor is a method.
A better way to think about it is that the new operator returns the object and in the process of creating the object, calls the constructor. Another way to think about it (although this is only a way to think about it, it isn't technically correct) is simply that the return type is implied by convention. A good place to read more about this is to read about new in the context of C++. The constructor's role is not to create the object but rather to initialize the memory contained within the object.
Default access for a constructor in Java is package private just like any other method. (One such source: http://www.javabeginner.com/learn-java/introduction-to-java-access-modifiers and from the horse's mouth: http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
Yes, constructors can be private. This is done when you want tighter or alternate control over instance creation such as with factory methods or with a pattern such as a Singleton.
It is a method but it is not called directly. It is a special type of method invoked on your behalf when you create a new object.
Constructors don't return anything, they create new objects.
The default is package private. So public to any class within the package but not visible to code outside of the package.
Thoughts on Tomcat performance and scalability: This is a highly variable situation based on your server hardware and types of requests and of course the quality, efficiency and memory footprint of the code serving each request.
Your lower bound on concurrent requests was 500. Consider that you probably want to create a thread for each request and given a 1MB stack per thread you're looking .5 GB just for thread stack space. And this is before heap memory and the performance overhead of allocating that many threads. I think that if need to handle that many requests at a time you might want to consider a more heavy duty server like JBoss.
A constructor can be declared private for any class.
A constructor is a special method that returns an instance of the class it belongs to, therefore you do not need to specify a constructors return type.
Package private is the right answer as pointed out below.
Yes -- factory instance singletons often use this pattern, to force users to init their class via static factory method.
Yes, it's a method
Because that is what a constructor does - it constructs. (it's assumed the result of construction will be returned)
same as methods
With regards to your Tomcat question, it depends on which version of Tomcat, which IO model it's using (e.g., NIO versus historical network IO modules), and your configuration. Single Tomcat's can process hundreds of requests at a time, although the concurrency is tune-able (each request will be handled by a distinct thread or thread from a pool).
The default access modifier of a constructor is CLASS ACCESS MODIFIER,
If a class is public , then access modifier of a constructor is public. If the class is default , then constructor is also default.
Constructor can be created as a private in any case.
Constructor is a special type of method which can be automatically called when we
are creating object for the corresponding class.
Constructor does not contain any return values. It just create new objects. Should not provide any return type for constructor.
The default access specifier of the constructor is public
Yes.
Yes.
because a constructor is called by new. What returns the object is the new, the constructor simply sets up the internal state.
Public.
I have a method that takes an enum as a parameter and returns some information dependent on that parameter. However, that enum contains some values which should not be handled, and should raise an error condition. Currently the method throws an IllegalArgumentException but I would like this to be a checked exception to force callers to catch it (and return gracefully, logging an error). Is there something suitable or should I create my own Exception subclass?
I'm open to other patterns as well. A reasonable reaction would be that all values of the enum should be handled, but that isn't the case. When a new value is added to the enum, I want to make sure that this method does the right thing - alerting a human is preferable to using some default return value in this case.
Thanks for any advice.
You can certainly create a checked exception of your own (such as UnhandledEnumType), or you could catch and handle the IllegalArgumentException. It sounds a little fishy that only some values of the enum should be handled. One of the purposes of an enum is to bind values to a certain set of values, and I would expect all to be handled. If you're worried about new ones being added, you should have a test that tests that all values are properly handled (by using the values() method of the enum to ensure they are all tested).
The questions are:
how "normal" are cases when the method is called with an unsuitable enum parameter?
can you handle these cases gracefully and then continue processing?
From what you describe, it is not "normal" (happens only when a new enum value is added and the method is not updated properly - i.e. when a bug was introduced). So to me this sounds more like a case for RuntimeException (i.e. unchecked). Callers of this method can still catch an unchecked exception if they really want to, but they are not forced to.
OTOH I would try to eliminate the case you describe, by moving the data your method is returning right inside the enum. This way whenever a new enum value is added, there is no way the relevant data could be forgotten.
If you are interested, you may want to check out this tutorial.
How about InstantiationException?
Thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated. The instantiation can fail for a variety of reasons including but not limited to:
the class object represents an abstract class, an interface, an array class, a primitive type, or void
the class has no nullary constructor
In Java, for each object, a new copy of instance variables is created which can be accessed using the object reference.
But in case of an instance method, only one copy of it(instance method) exists.
How is this method accessed by various object references?
The byte code (or native code if it's JIT'd) for the method is stored in one location. When the method is called, a pointer (under the hood, aka reference at a higher level) to the instance object is passed as the first argument so the method code can operate on that specific instance - have access to its fields, etc. In order to save space without additional performance cost, the calling mechanism in Java is quite a bit more complicated than C++, especially for interface methods.
Methods and fields are completely different. Methods apply to all instances of the object, but fields are per instance.
One way to think of it:
pretend the method is "global" to all instances, but it is "passed" an instance of the object via the "this" reference.
Methods can change the state of a particular instance, but they themselves are stateless.
Behind the scenes a reference to the object is passed to the method as part of the call. It may be useful to look at Java's reflection classes, Method.invoke() in particular.
From a previous answer of mine:
I'm sure the actual implementation is quite different, but let me explain my notion of method dispatch, which models observed behavior accurately.
Pretend that each class has a hash table that maps method signatures (name and parameter types) to an actual chunk of code to implement the method. When the virtual machine attempts to invoke a method on an instance, it gets the object's class, and looks up the requested signature in the class's table. If a method body is found, it is invoked, providing the original object as a reference called this.
Otherwise, the parent class of the class is obtained, and the lookup is repeated there. This proceeds until the method is found, or there are no more parent classes—which results in a NoSuchMethodError.
If a super class and a sub class both have an entry in their tables for the same method signature, the sub class's version is encountered first, and the super class's version is never used—this is an "override".
the implied reference "this" is passed in to each method, which of course you can reference explicitly
I'm assuming you're meaning on a simplistic level, as in how you actually do the call.
I'm also assuming you're refering to a method that has the static modifier in its signature, ie:
public static int getNum()
{
// code in here
return num;
}
If this is what you mean, and this was part of a class called 'SomeClass', then it would be accessed via the method call SomeClass.getNum(). ie, you put the actual class name before the method.
If this is not what you mean, ignore my answer :)