I have a class Dog extends Animal.
Then I call the hashCode() method as follows.
Animal animal = new Dog(200);
System.out.println(animal.hashCode());
Here,
If I've overridden the hashCode() in the Dog class it will be returned.
Else if I've overridden the hashCode() in the Dog class it will be returned.
Else some integer returned.
I wanna know...
Why does it call the hashCode() of the super class when it is not
overriden in the Dog class? How and what the 'some integer' generated
When the hashCode is not generated in anywhere. (I have heard that it
is the memory location of the object but not sure.)
This is referred to as method overriding. The hashCode method is defined in java.lang.Object, basically the top of the object heirarchy, so it is always available to any Object defined in Java. If the method is not overriden in your specific subclass or one of its parents, the default behavior defined in java.lang.Object will be invoked.
You typically should not worry about what the internal implementation of a hash code is in a parent object, but the default implementation does use the internal address of the Object. Note that this internal address is precisely that - an interpreted address that the JVM uses internally, that should not be depended upon by an application to be anything particularly meaningful.
You can read more about how overriding works in the Java Language Specification - Section 8.4.8.
In java every class, if not explitcitly mentioned, will have Object class as its parent class. As Object class defines the hashcode method this is avilable even if you don't define in your class. And yes, in java the default hashcode implemention is to return the memory location of the object. In a way this looks correct way as if two object are at same memory location than they must be same.
hasCode() is form parent class object so if you haven't override it then parent method will be called. I think what you refer to as some integer is the hashCode generated at the super parent Object. Which suggest you haven't override the hashCode in Animal class.
In general if a super class method is not overridden then the immediate parent's method will be called.
First In java every class, if not explitcitly mentioned, will have Object class as its parent class
Java doesn't generate hashCode(), i.e. This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.
Most classes (especially if you are going to use it in any of the Collection API) specially in hashcontainer(HashSet and HashMap) should implement their own HashCode (and by contract their own equals method).
If you are interested to know when to implement hashCode() and equals() you can visit this site http://www.javabeat.net/2007/08/hashcode-and-equals-methods/
Related
Why does the Collection interface have equals(Object o) and hashCode(), given that any implementation will have those by default (inherited from Object) ?
From the Collection JavaDoc:
While
the Collection interface adds no stipulations to the general contract
for the Object.equals, programmers who implement the Collection
interface "directly" (in other words, create a class that is a
Collection but is not a Set or a List) must exercise care if they
choose to override the Object.equals. It is not necessary to do so,
and the simplest course of action is to rely on Object's
implementation, but the implementor may wish to implement a "value
comparison" in place of the default "reference comparison." (The List
and Set interfaces mandate such value comparisons.)
The general contract for the Object.equals method states that equals
must be symmetric (in other words, a.equals(b) if and only if
b.equals(a)). The contracts for List.equals and Set.equals state that
lists are only equal to other lists, and sets to other sets. Thus, a
custom equals method for a collection class that implements neither
the List nor Set interface must return false when this collection is
compared to any list or set. (By the same logic, it is not possible to
write a class that correctly implements both the Set and List
interfaces.)
and
While the Collection interface adds no stipulations to the general contract for the Object.hashCode method, programmers should take note that any class that overrides the Object.equals method must also override the Object.hashCode method in order to satisfy the general contract for the Object.hashCode method. In particular, c1.equals(c2) implies that c1.hashCode()==c2.hashCode().
To answer your specific question: why does it have these methods? It's done simply for convenience to be able to include Java Docs giving hints as to what implementers should do with these methods (e.g. comparing equality of values rather than references).
To add to the other great answers. In the Collections interface, the equals method is defined in that interface to make some decisions in the way equaling two instances of collection should work. From the JAVA 8 documentation:
More generally, implementations of the various Collections Framework
interfaces are free to take advantage of the specified behavior of
underlying Object methods wherever the implementor deems it
appropriate.
So you don’t add methods from the Object class for any other reason that giving more definitiveness to the java doc. This is the reason why you don’t count those methods in the abstract methods in the abstract methods of an interface.
Moreover, in JAVA 8, along the same line of reasoning, default methods from the Object class are not allowed and will generate a compile error. I believe it’s was done to prevent this type of confusion. So if you try to create a default method called hashCode(), for example, it will not compile.
Here is a more in-depth explanation for this behavior in JAVA 8 from the Lambda FAQ:
An interface cannot provide a default implementation for any of the
methods of the Object class. This is a consequence of the “class wins”
rule for method resolution: a method found on the superclass chain
always takes precedence over any default methods that appear in any
superinterface. In particular, this means one cannot provide a default
implementation for equals, hashCode, or toString from within an
interface.
This seems odd at first, given that some interfaces actually define
their equals behavior in documentation. The List interface is an
example. So, why not allow this?
One reason is that it would become more difficult to reason about when
a default method is invoked. The current rules are simple: if a class
implements a method, that always wins over a default implementation.
Since all instances of interfaces are subclasses of Object, all
instances of interfaces have non-default implementations of equals,
hashCode, and toString already. Therefore, a default version of these
on an interface is always useless, and it may as well not compile.
Another reason is that providing default implementations of these
methods in an interface is most likely misguided. These methods
perform computations over the object’s state, but the interface, in
general, has no access to state; only the implementing class has
access to this state. Therefore, the class itself should provide the
implementations, and default methods are unlikely to be useful.
Just to add to the great answers above, it makes sense to have the 'equals' or `hashCode' methods in this scenario:
Collection<Whatever> list1 = getArrayList();
Collection<Whatever> list2 = getAnotherArrayList();
if(list1.equals(list2)){
// do something
}
In the absence of the equals method in the interface, we'll be forced to use concrete types, which is generally not a good practice :
ArrayList<Whatever> list1 = getArrayList();
ArrayList<Whatever> list2 = getAnotherArrayList();
if(list1.equals(list2)){
// do something
}
I am in the process of migrating to java from c++ and consider myself a java noob. I have been looking recently at a vast code base with several examples of the kind public class Myclass implements Cloneable{...} with no implementation of the clone function. I fail to understand the advantages of this pattern. Are there any? If you choose not to implement the clone function, why derive it from Cloneable? Also are there any lombok anotations which provide some default clone functions?
If a class does not implement the Cloneable interface, calling clone on an instance of the class results in a CloneNotSupportedException. The java.lang.Object already implements a clone method (this method is not abstract), so subclasses are not required to implement it. The clone method of java.lang.Object performs a shallow copy of the instance.
If you choose not to implement the clone function, why derive it from
Cloneable?
The clone() method doesn't derive from the Cloneable interface. It comes from the Object class.
Cloneable is simply a marker interface. It is used at runtime to valid the behavior if the clone() method is called on a instance of a class.
Java has chosen a design model where by default the object owns the clone() method. It is a design choice you may like or not but anyway, it is like that
Concretely, if you call clone() on a object and the class of the object doesn't implement Clonable, the JVM will at runtime throw a CloneNotSupportedException exception. In a same way, some classes throw UnsupportedOperationException if one of their method is not implemented.
Also are there any lombok anotations which provide some default clone
functions?
By default, clone() performs a shallow copy of the current object. That is, a new instance is created for the object you are cloning but all object fields that it owns are not cloned. Indeed, the fields of the cloned object still reference the same objects than those in the original instance. Only fields with primitive types (int, float, boolean, etc...) are cloned.
If you need to have a different behavior in the clone() method, Lombok cannot guess what is the behavior you want to have. So, no it makes no sense to use it to generate the implementation of the clone() method.
There is actually a #Wither annotation in lombok:
https://projectlombok.org/features/experimental/Wither.html
But you could also just create a new object passing parameters to a constructor.
In programming language, if you want that a child object should act as a substitute to parent & still it should not loose its own identity (of being child), you must have parent's permission. And that is why we make such methods virtual in C# or C++. And this becomes a complete hiding. Is the complete hiding considered as overriding in java? 99% of time I have wrong concept here because I think I am considering it only hiding. Can an overriden function be a complete hiding as fas as only JAVA is concerned?
Liskkiov's principle of substitution is linked to a function returning an abstract parent implementation instead of concrete child implementation. For example
ArrayList getList vs List getList
In the above example in the first case the getList method returns a concrete List implementation and in the second case the getList method returns an instance of the List interface. Now as per Liskov principle of substitution the second approach should be used as the second method can be overriden by subclasses to return different concrete implementations of List while in the first instance only an ArrayList of sub classes of ArrayList can be returned. So the first case is less abstract than the second case and as per Liskov's substitution principle the parent implementation should be as abstract as possible to allow the child to implement as freely as required.
Regarding method hiding so that is only possible with static methods. Overriding in java does not hide the method since its at instance level. However for static methods, since the method is at class level, polymorphism is not possible , and thus while they are inherited if a sub class creates a static method with the same name,arguments and return type and tries to access the method statically the sub classes version would be called and not the super classes version as the sub class has now effictively hidden the method from the super class.
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.
I think it might, because the Comparator interface contains an equals method.
From section 9.2 of the Java Language Specification:
If an interface has no direct superinterfaces, then the interface implicitly declares a public abstract member method m with signature s, return type r, and throws clause t corresponding to each public instance method m with signature s, return type r, and throws clause t declared in Object, unless a method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface. It is a compile-time error if the interface explicitly declares such a method m in the case where m is declared to be final in Object.
This allows you to call any of the Object methods via a reference of an interface type - which makes sense, given that the implementation will certainly be a subclass of Object.
EDIT: In the case of Comparator, it so happens that equals is explicitly redeclared, in order to provide more documentation. However, you'd be able to call equals on a Comparator reference anyway.
No interface implements Object class but the implementation does
In Java, every class will ultimately extend Object. While you can't instanciate Comparator itself, all comparator implementations will still extend Object.
The equals() method is redeclared in Comparator in order to adapt the Javadoc for the special contract that Comparator imposes on equals()
No interfaces ever extends/inherit an Object. Only it's implemented classes does extends Object implicitly (if not explicitly extended).
The Comparator.equals() method follows the same signature as Object.equals() method. The reason for this is stated on the JavaDoc:
However, overriding this method may,
in some cases, improve performance by
allowing programs to determine that
two distinct comparators impose the
same order.
Interface types are not officially subtypes of Object, but behave as if they were:
They also implicitly declare all the methods of Object (as quoted by Jon)
They can be converted to Object by an widening conversion without an explicit cast
All objects of the interface type are automatically objects of the object type
In this case, the interface type redeclares the equals method in a compatible way, and the implementation from Object is used if the implementing class does not provide its own implementation.
The specification here is done in a way that the default implementation from Object.equals also fits the specification of Comparator.equals, and that every (conformant) implementation of Comparator.equals also fits the specification of Object.equals.
Please refer below link
http://www.docjar.com/html/api/java/util/Comparator.java.html
You can see in the code that Comparator interface has its own equals method.
In java, an interface can never be created by inheriting it from a class. So, no, Comparator interface doesn't inherit Object class.
The interfaces are like Roles and its responsibilities are declared as interface methods.
Comparator being the interface just lists all the responsibilities which needs to be provided by a class which implements this interface.
The object of the class which implements Comparator will be subclass of the Object class.