How one class inherits all properties of Object class without actually using "extends" keyword? - Java @ Desk

Saturday, February 8, 2014

How one class inherits all properties of Object class without actually using "extends" keyword?

How one class inherits all properties of Object class without actually using "extends" keyword?

This is the most interesting question I came across in one of the linked in posts in Java group.
http://www.linkedin.com/groups/How-one-class-inherits-all-3983267.S.5832450660599083010?view=&gid=3983267&type=member&item=5832450660599083010#commentID_null

We all know Java does not support multiple inheritance, then how this thing works in Java.

Consider, I have 2 Java classes :
1) Class A {}
2) Class B {}

Java says, all classes extends an Object class by default. Then above two classes code implicitly or explicitly states that:
1) Class A extends Object {}
2) Class B extends Object {}

Now, if I require to class B to extend class A, then its breaking the core principal of Java that it does not support multiple inheritance as shown below:
Class B extends A extends Object {}
But its not like that. Multiple inheritance is :
Class extending Another Class, Another Class
Object   A 
  \     / 
   \   / 
    \ / 
     B 

But in above case, its like this

Object
  |
  A
  |
  B
i.e. When Class B says extends Class A, then Class A implicitly extends Object and Class B extends Class A. Consider below example
class Object { }

class Foo /* implicit extends Object */ {}

class FooBar extends Foo /* and therefore extends Object */ {}
The above case is not multiple inheritance.

This would be the case of multiple inheritance :

Object
|   |
A   B
 \ /
  C






No comments:

Post a Comment