new object is created or not? - java

I am reading Effective Java by Joshua Bloch. It confuses me in the item 1, where it states
A second advantage of static factory method is that, unlike constructors, they are not required to create a new object each time time they're invoked.
Isn't the static factory method meant to create a new object each time it is invoked?
//constructor
Orange(){
}
//static factory method
static Orange staticFactoryMethod(){
return new Orange;
}
Won't calling either the constructor or the staticFactoryMethod create an instance of Orange?
Orange orange=new Orange();
Orange orange=Orange.staticFactoryMethod();

A static factory does not always need to create a new object.
You can have this:
static Orange staticFactoryMethod(){
return new Orange();
}
But you can also have something like
static Orange staticFactoryMethod(){
Orange o = ... //find an orange in a basket of available oranges that has been already initialized
return o;
}

Take a look at Integer.valueOf(int i). If i is within the range -128 to 127 this method will not create a new Integer object but return a value from cache.

Isn't the static factory method is mean to create a new object each time it is invoked?
No. The purpose of a factory method is to return a suitable object. That object might be an object that was created earlier. It all depends on the intended semantics of the factory, and of the objects. For instance, it the objects are immutable and their object identity has no special significance, then sharing instances can be a worthwhile optimization.
For example, the Integer.valueOf(int) method returns an Integer method that may (for small integers) have been created and used previously. This has the advantage of reducing the number of Integer instances that are created ... and need to be garbage collected when they are finished with.
You could also argued that String.intern(String) is a form of factory method, though it has the unusual property that (in recent implementations) it never allocates new strings.
A third example is a thread or connection pool which tries to recycle objects that have been returned to the pool.
By contrast, if the "client" of your API has to use new to create instances, there is no opportunity for your API to do this kind of thing. That is Bloch's point.

Related

What is an immutable value class in Java? (Effective Java by Joshua Bloch)

I'm currently diving deep (at least relative to my limited knowledge as a programmer) into Java using Joshua Bloch's Effective Java.
In Item 1 under Creating and Destroying Objects, he states to consider static factory methods instead of constructors.
For example,
public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}
His reasoning in this item is clear to me, except for the part where he states that using static factory methods "allows an immutable value class". He expands on this statement: "guarantees that no two equal instances exist: a.equals(b) if and only if a == b". He states this is because using static factory methods doesn't require the creation of a new object every time they're invoked. Ergo, this makes classes instance-controlled: "allows classes to maintain strict control over what instances exist at any time."
I understand what these statements mean individually but cannot make sense of how exactly it relates to using static factory methods instead of constructors.
I'd appreciate any comments on helping me understand the matter, preferably with an example. Thank you in advance.
When you provide a constructor then the caller decides if a new object is created:
If the constructor for my FooBar class is publicly accessible then any code can run new FooBar() and it will create a new FooBar object (it could fail during construction, but it can't that expression can't just return an existing object instead).
If I made the constructor inaccessible but provide a factory method such as constructFooBar() then the code in the FooBar class can decide if a new object is created or not. So if some other code calls FooBar.constructFooBar() then the FooBar class alone can decide if it wants to construct a new instance, return an existing one or abort in osme other way (return null or throw an exception).
You can't have the guarantees you mention without controlling who can create instances, which means you can't make the constructors directly accessible.
Note that Boolean is not actually a good example of this, because it does have a publicly accessible constructor.
So this code:
Boolean b1 = Boolean.TRUE;
Boolean b2 = new Boolean(true);
System.out.println(b1.equals(b2));
System.out.println(b1 == b2);
would print true and false.

New objects: new operator vs serialization

As I understood from what I've read there are basically two ways to create completely new objects in Java: 1) by using new operator and 2) by means of serialization (for deep copying, for example). All other object manipulations (like assigning, for instance) deal with references to existing objects. But what is the difference between the two above mentioned ways in terms of inner logic? It seems that one difference is that serialization somehow doesn't use constructor methods. Am I right? Are there other differences?
By 'inner logic' I mean how the compiler (or whoever deals with it) creates object step-by-step, what algorithm it uses, what methods are used for that and so on. More like what Margaret Bloom was writing about in her answer but in more detail.
FURTHER CONFUSION CLARIFICATION:
So do I get it right that during deserialization the copy of the object:
class Class1 {
static ARRAY_LENGTH = 10;
public class1() {
int[] anArray = new int[ARRAY_LENGTH];
anArray[0] = 5;
...
anArray[9] = -2;
}
}
will include a copy of the array created elsehow (how? since no constructor has been called)? And furthermore, though the original array (before serialization) has been created by using static field (which is lost during serialization) its deserialized copy will nevetheless be identical to the original array?
Serialization and the new operator are completely different things, though they both result in a reference to a newly allocated object.
You can find detailed information about the new operator in chapter 15.9.4 Run-Time Evaluation of Class Instance Creation Expressions of the Java Language Specification.
At run time, evaluation of a class instance creation expression is as follows.
[...]
Next, space is allocated for the new class instance.
[...]
The new object contains new instances of all the fields declared in the specified
class type and all its superclasses.
[...]
Next, the actual arguments to the constructor are evaluated, left-to-right. [...]
Next, the selected constructor of the specified class type is invoked. This results in
invoking at least one constructor for each superclass of the class type.
The value of a class instance creation expression is a reference to the newly created
object of the specified class. Every time the expression is evaluated, a fresh object
is created.
Editing mine
So long story short, new allocates space for a new object (specifically space for its fields), initialize its fields with their default values and invokes the chosen constructor.
Java Serialization is another matter entirely.
The ability to store and retrieve JavaTM objects is essential to building all but the most transient applications. The key to storing and retrieving objects in a serialized form is representing the state of objects sufficient to reconstruct the object(s).
Emphasis mine
Which means that serialization was designed to allow the programmer to save objects states into a persistent medium (abstracted into stream within Java) and read them back.
As such, deserializiation does not invoke constructors since the object state is restored automatically by reading it out the stream. You can override the default behavior though.
Reading an object from the ObjectInputStream is analogous to creating a new object. Just as a new object's constructors are invoked in the order from the superclass to the subclass, an object being read from a stream is deserialized from superclass to subclass. The readObject or readObjectNoData method is called instead of the constructor for each Serializable subclass during deserialization.
Emphasis mine
Said that, I would like to stress out how using new and serialization are totally unrelated things from a conceptual point of view.
In the first case you are creating your own new object, in the latter you are reading a previously saved object (possibly by someone else).
Even though they can be thought as similar for their final result, you should have, in your mind, a really clear distinction between the twos.
New operator is use to create object in memory whereas serialization is the concept belongs to data persistence and it could also be used for creating a new object in memory.
If an object implements java.io.Serializable it will be marked as Serializable Object and data in object could be converted to byte stream (serialize) and we could use this byte stream data to create a new object in memory (desrialize). Java supports 2 objects for serialize and deserialize, they are ObjectInputStream and ObjectOutputStream
Disagree with deserializiation does not invoke constructors:
In fact, Deserializiation just does not invoke the constructors defined in the class body. As depends on java.reflect, it of course need to invoke constructors to produce a Object from a Class. It just invoke the custom constructors created by sun.reflect.ReflectionFactory.newConstructorForSerialization(Class<?> var1, Constructor var2).

Constructors does not have any return types but then how object is created?

According to the definitions of constructors they don't have any return types,but while creating object we often do A a = new A(); which is responsible for creating the object a.
A a=new A();
Can anyone help me understanding the issue,what is actually happening in the case of constructors while creation of Object.
Constructors don't have return types, correct. But the expression new A() does have a result: A reference to the newly-created object.
Here's what happens with new A():
An object is created
It's given the type A
The relevant A constructor is called with this referring to that new object
Once initialization is done, the expression completes
The result of the expression is the reference to the new object
This process is described in this tutorial on the Oracle Java site.
In many ways, it would be more accurate to call constructors initializers: The construction happens because of the new operator, not the constructor.
The fact that constructors don't actually do the construction is made particularly clear when an object is processed by multiple constructors, as is very common. Consider:
List<String> m = new LinkedList<String>();
One object is created (ignoring any fields the list may need to initialize), but five different constructors get called to initialize that one object, because LinkedList<E> subclasses java.util.AbstractSequentialList<E> which subclasses java.util.AbstractList<E> which subclasses java.util.AbstractCollection<E> which subclasses java.lang.Object, and each of those classes has to get its chance to initialize its part of the object that was created. So in order:
JVM creates the object
Object() is called to initialize Object stuff
AbstractCollection() is called to initialize its stuff
Then AbstractList()
Then AbstractSequentialList()
Then LinkedList()
And then finally the resulting (one) object's reference becomes the result of the new expression
One object, but five constructors required to initialize it. :-)
Constructors need not to return anything. They just constructs the current instance. That's all their job, part of object creation.
Creating objects:
A a = new A();
Declaration: The code set in bold are all variable declarations that associate a variable name with an object type.
Instantiation: The new keyword is a Java operator that creates the object.
Initialization: The new operator is followed by a call to a constructor, which initializes the new object.
Constructor declarations look like method declarations—except
that they use the name of the class and have no return type - from
the java constructor docs
To understand the constructor, it is similarly important to understand how it differs from a method.
Constructors have one purpose in life: to initialize the new object and it's fields. Nothing more. The new keyword handles the creation of memory space.
You shouldn't consider new A() to be a call to the constructor, because there are more things that happen, than just the constructor running. The major steps, when you run new A() are these.
A chunk of memory is set aside - just enough for storing an object of class A.
The constructor is run.
A reference to the chunk of memory that was set aside is returned.
So the constructor itself isn't actually returning anything - and it's an error to have return this; or anything similar inside the constructor.
Return statement inside a constructor doesn't logically makes sense because the purpose of the constructor is to perform initialization. The object has not been created yet, the actual construction of the object happens in JVM.

static factory method question!

in this site it says that a new object isnt being created each time , which leads to efficiency, but by what i can see an object is being created each time in the static method..
do not need to create a new object
upon each invocation - objects can be
cached and reused, if necessary.
http://www.javapractices.com/topic/TopicAction.do?Id=21
so why are the static factory methods are so efficient?
isnt writing something like this : Object obj=new Object is same as if i did Object obj=Someclass.GetObj();
class Someclass
{
public static Object GetObj()
{
return new Object
}
}
There is caching, but a new object is created either way...
Objects can be cached and reused. They aren't always. There are a number of other advantages, like:
better naming of the method
returning subclasses
There is an item in Effective Java for that, so go ahead and read it. The book is a must-read anyway.
Update: as I said, object can be cached. But it depends on the implementation. The one you show does not cache them. The one shown by Peter caches them. You have that option. With a constructor - you don't.
They are more flexible - for example if the input parameters for new object are not valid, you can return null or some null object implementation (=instance, which does nothing, but will not break your code by NullPointerException), or, as previously mentioned by others, you can cache created instances. There is another benefit from using factory methods over constructors - you can name them whatever you like, which can be more readable, if there are multiple constructors with lots of optional parameters.
EDIT: if you want to use only one instance, you can use this simple factory:
class Someclass{
private static Object o=new Object();
public static Object getObj(){
return o;
}
}
When you use new Object(), a new Object has to be created.
If you use a static factory, it can optionally create a new object, or it can reuse an existing one.
A simple example is using Integer.valueOf(int) instead of new Integer(int). The static factory has a cache of small integers and can save to the creation of a significant portion of integers. For some use cases this can be all the integers used. The later case will always create a new object which is relatively inefficient.
The link you presented provides very different explanation of a Factory Pattern. Generally factory pattern is used to obtain instances of classes whcih implement same interface but provide different behavior for the same contract. It allows us to choose different implementation at run time. Check out the example here:
http://www.allapplabs.com/java_design_patterns/factory_pattern.htm
Factory pattern is not generally used for caching objects. Singleton pattern is defined to ensure only one instance of the object is created.
The idea is that you use them as a strategy. If later you want to implement caching, you just change that method and add it in there. Compare this with having "new Bla()" scattered all over the code, and trying to implement caching for the Bla class.
Since the method is static, and usually just a few lines of code, it means it can be resolved at compile time, and even inlined.
Thus there is no advantage of using "new Bla()" instead of factory methods at all.
Using factory in some situations you could make your code more flexible, faster and also better readable.
For example, imagine, you have to write class which download some data from url
public class WavAudio {
private byte[] raw;
private static HashMap<String,WavAudio> cache;
private WavAudio(byte[] raw){
this.raw=raw;
}
public static loadFromUrl(String someUrl){
//If data has been loaded previously we don't have to do this more (faster..)
if (cache.containsKey(someUrl))
return cache.get(someUrl);
//Else we'll load data (that would take some time)
InputStream ires=(new URL(someUrl)).openStream();
ByteArrayOutputStream baos=new ByteArrayOutputStream();
byte[] raw = new byte[4096];
int nBytesRead;
while ((nBytesRead = ires.read(raw, 0, raw.length))>0)
baos.write(raw, 0, raw);
byte[] downloaded=baos.toByteArray();
WavAudio curr=new WavAudio(raw);
cache.put(someUrl,raw);
return raw;
}
public static void main(String[] args){
WavAudio wav=WavAudio.loadFromUrl("http://someUrl_1");
SomePlayer.play(wav); //the first melody is playing
WavAudio wav=WavAudio.loadFromUrl("http://someUrl_2");
SomePlayer.play(wav); //the second melody is playing
//won't be downloaded twice
WavAudio wav=WavAudio.loadFromUrl("http://someUrl_1");
SomePlayer.play(wav);
}
}

public static factory method

First of all please forgive me if its a really dumb question, I am just trying to learn this language to its core. I am reading Effective Java and the very first chapter talks about Static factory methods vs. Constructors. Their pros and cons. Few things that are confusing to me are:
class of an object returned by static factory method is nonpublic - what exactly does it mean?
unlike constructors static factory methods are not required to create a new object each time they are invoked - How does this happen? I am invoking factory method only to obtain a new object and do we put a check in factory method for checking if object already exists?
Thanks.
class of an object returned by static factory method is nonpublic -
what exactly does it mean?
It means that the actual class of the objects returned by a static factory method can be a subclass of the declared type, and this subclass does not have to be public. It's just another implementation detail that client code should not care about.
unlike constructors static factory methods are not required to create a new object each > time they are invoked - How does this happen? I am invoking factory method only to obtain a new object and do we put a check in factory method for checking if object already exists?
Yes, that's one way this could be done. But really, anything is possible.
First off, kudos to you for your choice in Java-lit: Bloch's book is an excellent primer.
To answer your 2nd question ('unlike constructors static factory methods are not required to create a new object each time they are invoked'), it's important to realize that what Bloch is saying here is that with a static factory you have the option of either: returning a new object or returning a pre-existing one. It all depends on what you want to do.
For example, let's suppose you have a really simple value class of type Money. Your static factory method probably should return a new instance -- that is, a new object with a specific value for Money. So, like this:
public class Money {
private Money(String amount) { ... } /* Note the 'private'-constructor */
public static Money newInstance(String amount) {
return new Money(amount);
}
}
But let's say you have some object that manages some resource and you want to synchronize access to that resource through some ResourceManager class. In that case you probably want your static factory method to return the same instance of itself to everyone -- forcing everyone to go through that same instance, so that that 1 instance can control the process. This follows the singleton-pattern. Something like this:
public ResourceManager {
private final static ResourceManager me = new ResourceManager();
private ResourceManager() { ... } /* Note the 'private'-constructor */
public static ResourceManager getSingleton() {
return ResourceManager.me;
}
}
The above method forces your user to only ever be able to use a single instance, allowing you to precisely control who(and when) has access to whatever it is you are managing.
To answer your first question, consider this (admittedly not the best example, it's pretty ad-hoc):
public class Money {
private Money(String amount) { ... }
public static Money getLocalizedMoney( MoneyType localizedMoneyType, String amount ) {
switch( localizedMoneyType ) {
case MoneyType.US:
return new Money_US( amount );
case MoneyType.BR:
return new Money_BR( amount );
default:
return new Money_US( amount );
}
}
}
public class Money_US extends Money { ... }
public class Money_BR extends Money { ... }
Note how I can now do this:
Money money = Money.getLocalizedMoney( user_selected_money_type );
saveLocalizedMoney( money );
Again, a really contrived-example but hopefully it helps you see more or less what Bloch was getting at with that point.
The other answers were good -- I just think that, as a beginner, sometimes it helps to see some actual code.
When you use the new keyword then you as the developer know that the JDK will create a new instace of that object. What the author is saying, when you use a static method, the developer no longer knows if the method is creating a new instance or possibly doing something else. Something else can be, reusing cached data, object pooling, creating a private implementation and returning a subclass of the class.
class of an object returned by static factory method is nonpublic
Frequently a static factory method will return either an an object typed as an interface (most common), or sometimes some base class (less common). In either case, you don't know the exact class of the returned object.
The advantage of this is getting an object whose behaviour you know without worrying about the messy details of what class it instantiates.
unlike constructors static factory methods are not required to create a new object each time they are invoked
To understand this, consider the case of working with a singleton. You may call .getInstance() on some factory classes to get the singleton instance of an certain object. Typically, what this does is create an instance of the object if it doesn't already exist, or give you the existing instance if it already does. In either case, you get back a copy of the object. But you don't (and won't) know if this singleton had to be created, or if one had already been constructed previously.
The advantage of this is that the lifecycle of the object and when it is created is managed for you.
Both of your questions can be answered by looking at some code that makes use of both of these properties of static factory methods. I suggest looking at Guava's ImmutableList.
Note how the no-arg factory method of() always returns the same instance (it doesn't create a new instance each time). If you look carefully, you'll also notice that its copyOf(Iterable) factory method actually returns the object that is passed to it if that object is itself an ImmutableList. Both of these are taking advantage of the fact that an ImmutableList is guaranteed to never change.
Notice also how various factory methods in it return different subclasses, such as EmptyImmutableList, SingletonImmutableList and RegularImmutableList, without exposing the types of those objects. The method signatures just show that they return ImmutableList, and all subclasses of ImmutableList have package-private (default) visibility, making them invisible to library users. This gives all the advantages of multiple implementation classes without adding any complexity from the user's perspective, since they are only allowed to view ImmutableList as a single type.
In addition to ImmutableList, most instantiable classes in Guava utilize static factory methods. Guava also exemplifies a lot of the principles set forth in Effective Java (not surprising, given that it was designed by those principles and with guidance from Josh Bloch himself), so you may find it useful to take a look at it more as you're working through the book.

Categories