When a class is declared as final, is it possible to clone or serialize it's objects? Or is this impossible because final prevents the extending of subclasses, therefore preventing cloning and serialization from implemented?
Final for classes --> You can't extend the class.
Final for objects --> You can't change the reference to the object.
Serializable/cloning--- > These concepts are for objects. You implement an interface to make the object of a perticular class Serializable/Cloneable.
So, yes, when a class is declared as Final, it is possible to Serialize/clone its objects provided you implement the necessary interfaces.
I think you may be not clear on some OOP concepts and their Java implementation.
You extend classes, while you serialize and clone objects.
There is a Singleton pattern that allows only a single object to be created, but that is a whole other story.
Related
I have the interface of an object. I don't know if the implementation is serializable or not. Nor Cloneable.
And I don't have getters of object properties, actually, I don't know the properties either.
Can I still clone the object?
I mean, can I do something like:
public void copyMyObject(MyObject myObject){
this.copyOfMyObject = ...//? can I make a deep copy?
}
I guess not...but maybe I am missing something.
Well ... it depends.
You can serialize an object if the object's actual class implements Serializable ... and the rest1. The actual type may be different to the (static) type of the variable where you are getting the object's reference from.
But if not, then you are not missing something. Deep copying an object that doesn't implement its own deep copy methods, getters and setters, or some form of serialization, would involve some extremely nasty coding2.
You are better off designing your classes so that they can be serialized / cloned. Or, so that you don't need to clone them.
Note that there are a few Java classes that would be impossible to clone correctly even by "nasty" means. Examples include Thread, Socket, Class, ClassLoader and some key awt classes. So if your (hypothetical) application design depended on (say) being able to clone a running thread, that design would not be implementable.
1 - Instance fields that are not transient and not null need to be serializable as well. And so on.
2 - For example, you could conceivably make use of abstraction breaking reflection and use of the Unsafe to replicate what the object serialization implementation does under the hood ... without the Serializable type check. It is a bad idea though.
In a class, I want to define an empty object and use it anywhere we need it. This object needs to be immutable to avoid accidentally modification. If this object is defined as a public static final member of the class, the object could be changed if the class itself is mutable.
What's the good way to create an immutable object in a mutable class?
If you need to make a class immutable then you need to fulfill this requirements:
all its fields final
the class declared as final
the this reference is not allowed to escape during construction
Any fields which refer to mutable data objects are:
private
have no setter method
they are never directly returned of otherwise exposed to a caller
if they are changed internally in the class this change is not visible and has no effect outside of the class
If you cannot modify the class to make it immutable (final class with final fields, etc.) than just write yourself an immutable wrapper (proxy from GOF?) and use it instead. Inside it can has a delegate to your original class instance.
I have read and have always been told that immutable classes must be final . but i was wondering if it is possible to have a non final class object as immutable one.
in this link (Why would one declare an immutable class final in Java?) what if the immutable class methods are final and cannot be overriden . And if all the members of the class are final, then also the object of that class can be immutable( unless they reference to a mutable object). Please tell me if am wrong and get ticked :)
If you can extend an immutable class (which means it's not final), you can add mutable properties to the sub-class, which would make your sub-class mutable, and therefore the base class would also be mutable, since it can have mutable sub-classes.
An immutable class doesn't necessarily need to be final, but you need to prevent it from being subclassed, e.g. by not having public or protected constructors.
For example, Guava's ImmutableList class isn't final, but it is immutable, as described in the Javadoc.
For creating immutable class it is not mandatory to mark the class as final.
Let me take one of such example from java classes itself "BigInteger" class is immutable but its not final.
Actually Immutability is a concept according to which ones the object created then it can not be modified.
Let's think from JVM point of view, from JVM point of view all threads must share the same copy of the object and it is fully constructed before any thread accesses it and the state of the object doesn't change after its construction.
Immutability means there is no way yo change the state of the object once it is created and this is achieved by three thumb rules which makes the compiler to recognize that class is immutable and they are as follows :-
all non private fields should be final
make sure there is no method in the class that can change the fields of the object either directly or indirectly
any object reference defined in the class can't be modified outside from the class
For more information refer to the below URL
http://javaunturnedtopics.blogspot.in/2016/07/can-we-create-immutable-class-without.html
I have been programming in Java for quite some time, but when I tried to explain what an java.lang.Object class is to a friend, I could not come up with more than a simple one-liner:
All objects in Java extend java.lang.Object implicitly
I was not quite sure why it should do so.
So, I looked upon the source code on GrepCode, hoping that I can find some clues. Now I know what a java.lang.Object is and what it does, I want to know if there was any specific reason as to why it was designed this way.
My question still prevails: why should every object extend java.lang.Object?
I would say that the reason is to have a common API for all objects in java to supports basic functionality like
synchronization - wait, notify, notifyAll
garbage collection - finalize
collection support - hashCode, equals
object cloning - clone
And every object
has a class it belongs to - getClass
can represent itself as a string, because we are
humans and can read strings - toString
I think the most important use of Object is not to provide common methods like toString() but to provide a common type that would hold all reference types.
C++ don't have an Object equivalent and people are still happy. But since Java don't have pointers and C++-like templates, Object is required to make implementations of Collections, etc. possible.
See also on discussions on reference and primitive types.
This is how the language is designed. Every object will inherit from the base class Object. This means that it's guaranteed for every object there will be certain methods, like toString(), equals(), hashCode(), etc.
I would say Design. Common/Mandatory methods which every Object should support written there and extending that class as a language specification.
You find the reasons here in Official Docs.
If we are saying this is an Object ,They must have the common methods, Which defined/decided by API.
Imagine the below methods for every class on your Own.
protected Object clone() throws CloneNotSupportedException
Creates and returns a copy of this object.
public boolean equals(Object obj)
Indicates whether some other object is "equal to" this one.
protected void finalize() throws Throwable
Called by the garbage collector on an object when garbage
collection determines that there are no more references to the object
public final Class getClass()
Returns the runtime class of an object.
public int hashCode()
Returns a hash code value for the object.
public String toString()
Returns a string representation of the object.
The notify, notifyAll, and wait methods of Object all play a part in synchronizing the activities of independently running threads in a program:
public final void notify()
public final void notifyAll()
public final void wait()
public final void wait(long timeout)
public final void wait(long timeout, int nanos)
So to reduce the pain, created a common and standard API.
Every Class extends Object class implicitly so that they provide basic features which according to Java recommendation every class should have. Such as clone(), equals(), hashCode(), toString(), etc.
By implicitly, it means that if you are not extending any class then only compiler will implicitly extends Object class.But if class already extends other class then compiler will not extend Object class. For eg.
Class A{
}
Class B extends A{
}
Here compiler will implicitly add extends Object class in class A declaration.
Class A extends Object{
}
Class B extends A{
}
As class A extends Object class so it will provide basic functionality of Object class such as equals(), toString(),etc. And since Class B extends class A which implicitly extends Class Object, so class B also provides all those features.
Thus by following this approach every class objects(variables) complies to features which every Java Object should have, without going for Multiple Inheritance (a class extending more than one class) which Java doesn't allows. This approach follows Multi-Level Inheritance.
This is done so as most of the basic functions like toString() etc would be automatically inherited and to your next question this is NOT multiple inheritence it is multilevel inheritence...
In multiple inheritence single class is derived from 2 or more base class whereas in multilevel as you have said it has a base class which is itself derived from Object class
Quoting Head first Java 2nd edition:
Without a common superclass for everything in Java, thereād be no way
for the developers of Java to create classes with methods that could
take your custom types... types they never knew about when they wrote
the ArrayList class.
Which essentially explains the need of a generic predefined class type in Java, which can be used to implement the different features provided by the language.
See the docs:
The Object class, in the java.lang package, sits at the top of the
class hierarchy tree. Every class is a descendant, direct or indirect,
of the Object class. Every class you use or write inherits the
instance methods of Object. You need not use any of these methods,
but, if you choose to do so, you may need to override them with code
that is specific to your class.
The Object class simply defines the basic state that all objects must have - Like comparing it to other objects.
It's the parent class of everything. It simply provides kind of template to all the derived objects.
It's a java design decision. It puts to use the concept of inheritance and re-usabilty. This ensures that all classes have some basic methods like wait(), toString() etc.
Object class is the most super class of java programming, It has predefined methods according to types, you can use those methods. & you don't need to extends object class anymore & anywhere it's implicitly there
Every class in Java is a descendent (direct or indirect) of the Object class. The Object class defines the basic state and behavior that all objects must have, such as the ability to compare oneself to another object, to convert to a string, to wait on a condition variable, to notify other objects that a condition variable has changed, and to return the object's class.
Serialization is a mechanism of storing the state of an object. Based on this definition we can say that the instance variables in an object can be serialized.
Methods are behaviors of the class.
We can set and get the state of an object using the methods. So the methods are related to the instance variables of the class.
Then why can't we serialize the methods in Java ?
What do you plan on 'after' serializing the methods? The state of the object has to be by definition should be only its members. Their behaviors would not come into picture. And serialization is saving the state of the object and not its behaviors.
Methods are always serialized: as bytecode in a class file. There is no practical need to serialize them again.
From OOP perspective, the state of an object is the total state of its non-static fields. Methods are a way to define the object behaviour and are common to all instances (objects) of that class, so they are defined as fields at the Class object not as a field of the object (instance) itself. So serializing the object would store its state thus only its fields, but if you serialize the Class object of your objects you would be serializing the methods of those objects (thought I see no reason why would someone bother himself to do so).
Because method the same for all instances of class, they only driven by its data. If you have class definition in your app - you have it's methods.
But data can change from instance to instance.
A method per say does not have any state, and a serialized method call cannot be used for anything. On the other hand, a serialized thread is conceptually a snapshot or checkpoint of a computation, and that would be useful.
However, threads are not serializable in Java, and it would be really difficult to implement this. (For example, how would you cope with the case where the code of one of the active methods was changed between serializing and deserializing a thread?)