In Java, all classes are extending Object class implicitly , on top of that at max only one class can be inherited. So is it like , implicitly Java is allowing us to extend 2 classes or it is some other logic Java is following?
8 Answers
No. In Java, a class can only inherit from one class and by default this is the Object class that you refer to. We can however specify a different class to inherit from (using the 'extends' keyword). However, this parent class will itself have a parent class and so on until ultimately we get back to the Object class. Perhaps an example will help:
class Animal {
}
class Cat extends Animal {
}
class Tiger extends Cat {
}
In the above example Tiger inherits from Cat which inherits from Animal which (by default) inherits from Object.
Hope this clears things up a touch.
Comments
No. You're allowed to extend only one class, but this class can itself extend another one. If you don't specify any superclass in the extends clause, you extend from Object directly. If you specify a class in the extends clause, you extend from this class, which extends its own superclass, etc., until Object.
Comments
"No, this is a misunderstanding of implicit object inheritance. Every Java class is ultimately descended from the Object superclass, whether there is an extends Object statement or not. If you extend an Application Programming Interface (API) class, the Object inheritance is passed down through that immediate superclass, not from the superclass and the Object class too. Implicit inheritance from the Object class descends through a single line of parent classes to ensure all user defined classes have the standard toString(), equals() and hashCode() methods. "
Others answers here - Inheritance in java and Superclasses(Object, Class)
Comments
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyExamples
{
public class Object
{
static void Main(string[] args)
{
}
public void A1()
{
}
}
public class B : Object
{
public void B1()
{
}
}
public class D : B
{
public void D1()
{
D obj = new D();
obj.A1();
}
}
}
//This is something like this if a class extends another class then i am thinking that it will not extend object class anymore //but the parent class will be implementing object class...and this is equivalent to multilevel inheritance //like D extends B but B doesnt extend object class anymore //and B by default extends object class. So if we create an object of D then we can access object class too
Comments
class A //internally extends Object Class
{
}
public class B extends A //JVM wont extend object class here because A already extends Object
{
}