Why does every object in Java implicitly extend java.lang.Object class? - java

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.

Related

Can Polymorphysim be achived using composition instead of inheritance ? (in Java)

I am learning Java, I know what inheritance and composition is, I saw numerous examples of polymorphysim showed using inheritance, so my first question is,can same be done using composition? If yes, please show with a small example.
My second question is, can it be said that polymorpysim is basically method overloading and/or is method overiding ? if yes, then why ?
First question
Polymorphism can be achieved in Java in two ways:
Through class inheritance: class A extends B
Through interface implementation: class A implements C.
In the later case, to properly implement A's behaviour, it can be done though composition, making A delegate over some other class/es which do the tasks specified in Interface C.
Example: Let's suppose we have already some class imeplementing interface C:
class X implements C
{
public String getName() {...}
public int getAge() {...}
}
How can we create a new class implementing C with the same behaviour of X? Like this:
class A implements C
{
private C x=new X();
public String getName() {return x.getName();}
public int getAge() {return x.getAge();}
}
Second question
No, polymorphism is not method overloading and/or method overriding (in fact, overloading has nothing to do with Object Oriented Design):
Method overloading consists on creating a new method with the same name that some other (maybe inherited) method in the same class but with a different signature (=parameter numbers or types). Adding new methods is OK, but that is not the aim of polymorphism.
Method overriding consists on setting a new body to an inherited method, so that this new body will be executed in the current class instead of the inherited method's body. This is a advantage of polymorphism, still is not the base of it either.
Polymorphism, in brief, is the ability of a class to be used as different classes/interfaces.
No, not really. Polymorphism and composition or aggregation (composition is a more rigid form of aggregation wherein the composed objects' lifetimes are tied together) are different ways of reusing classes.
Composition involves aggregating multiple objects to form a single entity. Polymorphism involves multiple objects that share analogous behavior.
For example, a Car object might be composed of two Axle objects, a Chassis object, four Wheel objects (which themselves may be composed of a Rim, a Tire, six LugNuts and so on). When you instantiate a Car, your Car constructor would instantiate all the parts that go along with it. That's composition. (Aggregation would use all the same part objects but not necessarily instantiate them in its constructor.)
A Car object might also not be useful on its own, but rather as a blueprint for numerous more specialized implementations of cars, such as SportsCar, SUVCar, SedanCar, and the like. In this case, the Car object might define a Car interface that would define common behaviors such as Steer, HitTheGas and Brake, but leave the implementations of those behaviors to the implementing classes. Then, a consumer of a Car object can declare an object of type Car, instantiate it as any of the implementing classes such as SportsCar, call the methods defined in the Car interface, and get the behavior implemented in the instantiated class. That's polymorphism.
For a decent tutorial on both, with some comparisons, have a look at this. Keep in mind that the UML diagrams have an inaccuracy: while the examples do indeed describe composition as opposed to aggregation, the related UML class diagrams have white diamonds where they should be black. UML class diagram syntax uses a white diamond for class associations that are aggregations and a black one for those that are compositions.
Also, this post has some good information, in particular tdammers's answer halfway down the page.
There is book answer, if one remember about all the firemans are fireman but some are drivers, chiefs etc. There you need polymorphism. There is things you can do with classes and it's a general idea in OOP as language constraints. Overriding is just what you can do with classes. Also permissions and local and/or global scopes. There is default constructor for any class. There is namespace scope, program, class etc.
All Classes and methods are functions but not all functions are methods
You can override class but not method. Those are static or volatile. Cos method can only return the value. So overriding the method has no sense. I hope this will turn you, if nothing, toward how it was meant to be. Inheritance is mechanism how polymorphism works.
My apologies for unintentional mistakes during too much data.

Java Interface in C++

first posting so please be gentle!
I have an interface that's like this
public interface I_Hospital{
public void registerObserver(I_Person p);
public void removeObserver(I_Person p);
public void notifyObservers();
public void addWard(Ward ward);
}
Now, if I want to recreate this in C++, is it correct to do the following:
IHospital.h
Class IHospital{
public:
virtual void registerObserver(IPerson p) = 0;
etc...
}
Is this the correct implementation on an Interface in C++??
Thanks, Patrick
Yes, you'd define an interface as an abstract class containing pure virtual functions (with the purity indicated by = 0), just like that. Like Java's interfaces, abstract classes can't be instantiated directly, but must be derived from by concrete classes which override and implement the pure virtual functions.
There are a couple of issues:
the keyword to introduce a class is class not Class
you'll want to take the IPerson parameter by reference, IPerson &, not by value; abstract classes can't be passed by value. The same probably applies to the Ward argument; even if it's not abstract, you probably want this class to refer to a ward (as the Java version would), not copy one. Unlike Java, passing a class object to a function will pass a copy of the object, unless you specifically request that it's passed by reference.
A Java interface provides methods that must be overridden by classes that inherit from that interface. This is akin to having an abstract C++ base class that pure virtual methods, like the one you've shown. So yes, that is the correct implementation. Also note that in base classes should have virtual destructors so that deleting a base class pointer to a derived instance correctly calls the derived and base class destructors.
Yes, this is as close as you can get to Java's concept of interfaces.
Note that C++ doesn't actually have a concept of an interface as a separate thing from a class. However, it is customary for C++ developers to refer to classes that have no data members and whose methods are all pure virtual as interfaces -- this is a distinction made by programmers, not the language itself.

Implicit inheritance working in Java

Can anyone tell me how the implicit inheritance works in java internally?
What I mean is if I create a class how exactly it extends the Object class in the JVM?
Thanks in advance.
Java forces inheritance on every class. If you do not explicitly inherit from a class, then by default Java assumes that you are inheriting from the class called Object, which does not do much, but does have several useful methods :
it implies that every class is descended from Object, since whatever class you inherit from must have inherited from something, which would be either Object or something that inherited from something, etc.
the concept of polymorphism implies that you could store any type of object in a variable whose type was Object
For all practical reasons, you can think that class X { is a syntax sugar for class X extends Object {—that's it.
Apart from the Object class, every class in Java must have a super-class.
There is nothing special about implicit inheritance. It is simply a syntactic shortcut that means you don't have to write extends Object. At a semantic level, implicit inheritance works exactly the same way as explicit inheritance.
In practice, this means that every class inherits certain standard methods from Object ... unless the methods are overridden. Examples include equals(Object), hashcode() and toString() which are frequently overridden, and getClass() that cannot be overridden.

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

Java doesn't allow multiple inheritance, but it allows implementing multiple interfaces. Why?
Because interfaces specify only what the class is doing, not how it is doing it.
The problem with multiple inheritance is that two classes may define different ways of doing the same thing, and the subclass can't choose which one to pick.
One of my college instructors explained it to me this way:
Suppose I have one class, which is a Toaster, and another class, which is NuclearBomb. They both might have a "darkness" setting. They both have an on() method. (One has an off(), the other doesn't.) If I want to create a class that's a subclass of both of these...as you can see, this is a problem that could really blow up in my face here.
So one of the main issues is that if you have two parent classes, they might have different implementations of the same feature — or possibly two different features with the same name, as in my instructor's example. Then you have to deal with deciding which one your subclass is going to use. There are ways of handling this, certainly — C++ does so — but the designers of Java felt that this would make things too complicated.
With an interface, though, you're describing something the class is capable of doing, rather than borrowing another class's method of doing something. Multiple interfaces are much less likely to cause tricky conflicts that need to be resolved than are multiple parent classes.
Because inheritance is overused even when you can't say "hey, that method looks useful, I'll extend that class as well".
public class MyGodClass extends AppDomainObject, HttpServlet, MouseAdapter,
AbstractTableModel, AbstractListModel, AbstractList, AbstractMap, ...
The answer of this question is lies in the internal working of java compiler(constructor chaining).
If we see the internal working of java compiler:
public class Bank {
public void printBankBalance(){
System.out.println("10k");
}
}
class SBI extends Bank{
public void printBankBalance(){
System.out.println("20k");
}
}
After compiling this look like:
public class Bank {
public Bank(){
super();
}
public void printBankBalance(){
System.out.println("10k");
}
}
class SBI extends Bank {
SBI(){
super();
}
public void printBankBalance(){
System.out.println("20k");
}
}
when we extends class and create an object of it, one constructor chain will run till Object class.
Above code will run fine. but if we have another class called Car which extends Bank and one hybrid(multiple inheritance) class called SBICar:
class Car extends Bank {
Car() {
super();
}
public void run(){
System.out.println("99Km/h");
}
}
class SBICar extends Bank, Car {
SBICar() {
super(); //NOTE: compile time ambiguity.
}
public void run() {
System.out.println("99Km/h");
}
public void printBankBalance(){
System.out.println("20k");
}
}
In this case(SBICar) will fail to create constructor chain(compile time ambiguity).
For interfaces this is allowed because we cannot create an object of it.
For new concept of default and static method kindly refer default in interface.
Hope this will solve your query.
Thanks.
You can find accurate answer for this query in oracle documentation page about multiple inheritance
Multiple inheritance of state: Ability to inherit fields from multiple classes
One reason why the Java programming language does not permit you to extend more than one class is to avoid the issues of multiple inheritance of state, which is the ability to inherit fields from multiple classes
If multiple inheritance is allowed and When you create an object by instantiating that class, that object will inherit fields from all of the class's superclasses. It will cause two issues.
What if methods or constructors from different super classes instantiate the same field?
Which method or constructor will take precedence?
Multiple inheritance of implementation: Ability to inherit method definitions from multiple classes
Problems with this approach: name conflicts and ambiguity. If a subclass and superclass contain same method name (and signature), compiler can't determine which version to invoke.
But java supports this type of multiple inheritance with default methods, which have been introduced since Java 8 release. The Java compiler provides some rules to determine which default method a particular class uses.
Refer to below SE post for more details on resolving diamond problem:
What are the differences between abstract classes and interfaces in Java 8?
Multiple inheritance of type: Ability of a class to implement more than one interface.
Since interface does not contain mutable fields, you do not have to worry about problems that result from multiple inheritance of state here.
Java does not support multiple inheritance because of two reasons:
In java, every class is a child of Object class. When it inherits from more than one super class, sub class gets the ambiguity to
acquire the property of Object class..
In java every class has a constructor, if we write it explicitly or not at all. The first statement is calling super() to invoke the
supper class constructor. If the class has more than one super class, it
gets confused.
So when one class extends from more than one super class, we get compile time error.
Java supports multiple inheritance through interfaces only. A class can implement any number of interfaces but can extend only one class.
Multiple inheritance is not supported because it leads to deadly diamond problem. However, it can be solved but it leads to complex system so multiple inheritance has been dropped by Java founders.
In a white paper titled “Java: an Overview” by James Gosling in February 1995(link - page 2) gives an idea on why multiple inheritance is not supported in Java.
According to Gosling:
"JAVA omits many rarely used, poorly understood, confusing features of
C++ that in our experience bring more grief than benefit. This
primarily consists of operator overloading (although it does have
method overloading), multiple inheritance, and extensive automatic
coercions."
Implementing multiple interfaces is very useful and doesn't cause much problems to language implementers nor programmers. So it is allowed. Multiple inheritance while also useful, can cause serious problems to users (dreaded diamond of death). And most things you do with multiple inheritance can be also done by composition or using inner classes. So multiple inheritance is forbidden as bringing more problems than gains.
It is said that objects state is referred with respect to the fields in it and it would become ambiguous if too many classes were inherited. Here is the link
http://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html
Since this topic is not close I'll post this answer, I hope this helps someone to understand why java does not allow multiple inheritance.
Consider the following class:
public class Abc{
public void doSomething(){
}
}
In this case the class Abc does not extends nothing right? Not so fast, this class implicit extends the class Object, base class that allow everything work in java. Everything is an object.
If you try to use the class above you'll see that your IDE allow you to use methods like: equals(Object o), toString(), etc, but you didn't declare those methods, they came from the base class Object
You could try:
public class Abc extends String{
public void doSomething(){
}
}
This is fine, because your class will not implicit extends Object but will extends String because you said it. Consider the following change:
public class Abc{
public void doSomething(){
}
#Override
public String toString(){
return "hello";
}
}
Now your class will always return "hello" if you call toString().
Now imagine the following class:
public class Flyer{
public void makeFly(){
}
}
public class Bird extends Abc, Flyer{
public void doAnotherThing(){
}
}
Again class Flyer implicit extends Object which has the method toString(), any class will have this method since they all extends Object indirectly, so, if you call toString() from Bird, which toString() java would have to use? From Abc or Flyer? This will happen with any class that try to extends two or more classes, to avoid this kind of "method collision" they built the idea of interface, basically you could think them as an abstract class that does not extends Object indirectly. Since they are abstract they will have to be implemented by a class, which is an object (you cannot instanciate an interface alone, they must be implemented by a class), so everything will continue to work fine.
To differ classes from interfaces, the keyword implements was reserved just for interfaces.
You could implement any interface you like in the same class since they does not extends anything by default (but you could create a interface that extends another interface, but again, the "father" interface would not extends Object"), so an interface is just an interface and they will not suffer from "methods signature colissions", if they do the compiler will throw a warning to you and you will just have to change the method signature to fix it (signature = method name + params + return type).
public interface Flyer{
public void makeFly(); // <- method without implementation
}
public class Bird extends Abc implements Flyer{
public void doAnotherThing(){
}
#Override
public void makeFly(){ // <- implementation of Flyer interface
}
// Flyer does not have toString() method or any method from class Object,
// no method signature collision will happen here
}
For the same reason C# doesn't allow multiple inheritence but allows you to implement multiple interfaces.
The lesson learned from C++ w/ multiple inheritence was that it lead to more issues than it was worth.
An interface is a contract of things your class has to implement. You don't gain any functionality from the interface. Inheritence allows you to inherit the functionality of a parent class (and in multiple-inheritence, that can get extremely confusing).
Allowing multiple interfaces allows you to use Design Patterns (like Adapter) to solve the same types of issues you can solve using multiple inheritence, but in a much more reliable and predictable manner.
For example two class A,B having same method m1(). And class C extends both A, B.
class C extends A, B // for explaining purpose.
Now, class C will search the definition of m1. First, it will search in class if it didn't find then it will check to parents class. Both A, B having the definition So here ambiguity occur which definition should choose.
So JAVA DOESN'T SUPPORT MULTIPLE INHERITANCE.
in simple manner we all know, we can inherit(extends) one class but we can implements so many interfaces.. that is because in interfaces we don't give an implementation just say the functionality. suppose if java can extends so many classes and those have same methods.. in this point if we try to invoke super class method in the sub class what method suppose to run??, compiler get confused
example:- try to multiple extends
but in interfaces those methods don't have bodies we should implement those in sub class..
try to multiple implements
so no worries..
Multiple inheritance is not supported by class because of ambiguity.
(this point is explained clearly in above answers using super keyword)
Now for interfaces,
upto Java 7, interfaces could not define the implementation of methods. So if class implements from multiple interfaces having same method signature then implementation of that method is to be provided by that class.
from java 8 onwards, interfaces can also have implementation of methods. So if class implements two or more interfaces having same method signature with implementation, then it is mandated to implement the method in that class also.
From Java 9 onwards, interfaces can contain Static methods, Private methods, Private Static methods.
Modifications in features of Interfaces (over java version-7,8,9)
Because an interface is just a contract. And a class is actually a container for data.
Consider a scenario where Test1, Test2 and Test3 are three classes. The Test3 class inherits Test2 and Test1 classes. If Test1 and Test2 classes have same method and you call it from child class object, there will be ambiguity to call method of Test1 or Test2 class but there is no such ambiguity for interface as in interface no implementation is there.
Java does not support multiple inheritance , multipath and hybrid inheritance because of the following ambiguity
problem.
Scenario for multiple inheritance: Let us take class A , class B , class C. class A has alphabet(); method , class B has also alphabet(); method. Now class C extends A, B and we are creating object to the subclass i.e., class C , so C ob = new C(); Then if you want call those methods ob.alphabet(); which class method takes ? is class A method or class B method ? So in the JVM level ambiguity problem occurred. Thus Java does not support multiple inheritance.
multiple inheritance
Reference Link: https://plus.google.com/u/0/communities/102217496457095083679
Take for example the case where Class A has a getSomething method and class B has a getSomething method and class C extends A and B. What would happen if someone called C.getSomething? There is no way to determine which method to call.
Interfaces basically just specify what methods a implementing class needs to contain. A class that implements multiple interfaces just means that class has to implement the methods from all those interfaces. Whci would not lead to any issues as described above.
the image explaining the problem with multiple inheritances.
What is the inherited member of the derived class? it is still private or publically available in the derived class?
For not getting this type of problem in Java they removed multiple inheritance. This image is a simple example of an object-oriented programming problem.
* This is a simple answer since I'm a beginner in Java *
Consider there are three classes X,Y and Z.
So we are inheriting like X extends Y, Z
And both Y and Z is having a method alphabet() with same return type and arguments. This method alphabet() in Y says to display first alphabet and method alphabet in Z says display last alphabet.
So here comes ambiguity when alphabet() is called by X. Whether it says to display first or last alphabet???
So java is not supporting multiple inheritance.
In case of Interfaces, consider Y and Z as interfaces. So both will contain the declaration of method alphabet() but not the definition. It won't tell whether to display first alphabet or last alphabet or anything but just will declare a method alphabet(). So there is no reason to raise the ambiguity. We can define the method with anything we want inside class X.
So in a word, in Interfaces definition is done after implementation so no confusion.
It is a decision to keep the complexity low.
With hybrid inheritance, things would have been more complicated to implement, and anyways what is achievable by multiple inheritances is also with other ways.

Does removing an interface break code calling methods on the object?

I need to do some refactoring in Java, and I need to maintain some degree of binary compatibility. In this case I want to remove some legacy interfaces, that are not used anywhere anymore and which require a rather big (and also deprecated) external dependency.
I have class C that implements interface I, and I have code that calls a method (declared in the interface) on an instance of C. The calling code knows that it is using C, not just the interface.
class C implements I {
void theMethod(){} ; // is declared in the interface I
}
C object;
object.theMethod();
When I remove the interface from the class definition (but keep all the methods), will the calling code (which does not refer to the interface at all) still work (without a recompile)?
Yes, it will work - as long as it doesn't explicitly refer to interface I anywhere.
From JLS: Resolution of Symbolic References:
The binary representation of a class
or interface references other classes
and interfaces and their fields,
methods, and constructors
symbolically, using the binary names
(§13.1) of the other classes and
interfaces
Class ClientClass referring to field / method of class C contains no implicit references to interface I that class may implement.
It works as long as an object of class C is never referred to as I.
You can also refer to Evolving Java-based APIs part 2.
You might have a problem with the calling Code if it imports the Interface anywhere. If there is no import of the interface in any of the calling code, you can be reasonably confident that your refactoring will work as planned.

Categories