If Java can only extend one class, and every class extends java.lang.Object, how can it extend another class? And how come every class doesn't have written extends Object?
If java can only extend one class, and every class extends java.lang.Object, how can it extend another class?
When you say A extends B then it means that A extends B and B extends Object. One class can inherit from another which can inherit from another and at the top of the chain is java.lang.Object. Java doesn't support multiple inheritance , but supports multi-level inheritance.
how come every class doesn't have written "extends Object" ?
All classes extend Object implicitly , so it will be redundant coding.
Every class in Java extends implicitly class Object, and you only have the permission to extend one more class, and infinite number of interfaces.
Same as having one default constructor for each class if you didn't write a constructor.
So when you say
class A{
}
it is actually looks like this:
class A extends Object{
A(){
super();
}
}
But when you say when you say
class B extends A
In this case class B will have the features of class A, and because A extends Object, class B will also inherit class Object.
A -> Object
B -> A
So
B -> Object
Since java.lang.Object is the parent of every object in Java, you don't have to explicitly write extends Object
You can always extend any class. If you need to have behavior of 2 classes - you need to use interfaces for that
The one and only that you are allowed to extend also extends the class Object ultimately.Hence you are not extending twice.
Multiple inheritance is not supported in Java, you can only inherit in a straight line (so to speak). You use interfaces though, which are IMO much more powerfull. I never needed multiple inheritance, but I make heavy use of interfaces.
Basically instead of creating a second class, you define an Interface, and then let some class implement it. This can be a different class or the same.
All classes are already derived from Objects, you don't need to write that specifically.
Each of the following can extend the object to the left:
Object -> Vehicle -> Car -> Coupe -> Camaro
So for example, Coupe is extending Car, and it is not (directly) extending Object... it's just that if you keep going up the chain you'll eventually get to Object.
You couldn't however, have Coupe extend both Car and Truck
Here is an example showing the class hierarchy of Java's java.lang.Number class.
http://docs.oracle.com/javase/tutorial/java/data/numberclasses.html
As you can see, Integer class inherits from Number, and Number inherits from Object. So you can inherit multiple classes by chaining them.
In object-oriented programming (OOP), inheritance describes a relationship between two types, or classes, of objects in which one is said to be a subtype or child of the other.
A -> B -> C -> D
The child inherits features of the parent, allowing for shared functionality. For example, one might create a variable class Animal with features such as eating etc.; then define a subtype Dog that inherits those features without having to explicitly program them, while adding new features like chasing cats.
Multiple inheritance allows programmers to use more than one hierarchy simultaneously, such as allowing Dog to inherit from Robot character and Animal and access features from within all of those classes.
A
/ \
C D
\ /
E
Java uses the first model and therefore inheriting from object and another class doesn't cause a problem because it is hierarchical in nature.
Object -> Animal -> Dog -> Pit Bull
The reason that every object does not need to extend Object is because it happens implicitly.
Related
I want to have a list of objects that all inherit from the same interface that contains the function go().
public interface goers{
public void go();
}
Now I have 3 classes that all implement go, for the sake of simplicity let's just call them A, B, and C.
In another class I have a List<Class<? extends goers>> that I want to do.
for (Class<? extends goers> gos : list)
{
gos.go();
}
But it won't compile because the compiler doesn't pick up the go method from the interface being applied to all of the members of the list.
A List<Class<? extends goers>> doesn't have a goers instance that you can call .go() on. You just have classes, not any instances of that classes. There's nothing to call .go() on.
You could try instantiating those classes, or having a List<goers> in the first place, which lets you call it how interfaces are intended to be used.
Because go() is not a method of Class<T>, you cannot call that method on an instance of Class<T>. You have to use only methods of https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html.
If you want an instance of goers [sic - follow the naming conventions] you need to get one somehow. You could use, for example, https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#newInstance--.
Your essential problem is that you're using reflection, an advanced technique that is easy to abuse and hard to get right. Why don't you pass a list of instances of goers [sic - follow the naming conventions] instead of Class objects?
Everybody knows that in java we can only extend "ONE" class.
But for the sake of understanding:
Any Java class implicitly extends java.lang.Object
If class A extends class B, wouldn't class A extend both class B and java.lang.Object implicitly ?
In such a case we are extending two classes by default.
Why is it allowed if Java doesn't support multiple inheritance ?
That would be a multilevel inheritance.
You are mistaking multiple to multilevel.
A->B->C //This is multilevel inheritance which you are talking about
Multiple inheritance is like (which is not possible in java)
A
| |
B C
Java doesn't support multiple inheritance that makes any ambiguous cases to fade away. But careful implementation of implement keyword for implementing does give feel of multiple inheritance
Conclusion:
Class A can extend a class B which extends class C. This is still single inheritance. All the classes form a tree, where the root is the Object class, and each class (except of Object) has exactly one direct super-class (or parent class)
No, Java prevents a class from directly extending more than one super class. Class A can extend a class B which extends class C. This is still single inheritance. All the classes form a tree, where the root is the Object class, and each class (except of Object) has exactly one direct super-class (or parent class), which is either Object or some other class.
Whenever class A extends class B, class A no longer extends Java.lang.Object, but however: Since every class extends Java.lang.Object as you said earlier, then class B would extend Java.lang.Object and therefore class A is still a subclass of that particular class.
"Implicitly extends Object by default" means that if you don't see the extends keyword in the class declaration it "invisibly but directly" extends Object. If you see the extends keyword, the class does not directly extend Object, but the class mentioned in the extends clause. Now you have to traverse that hierarchy and at one point, you'll find a parent class with no "extends", and there the implicit inheritance strikes again.
All classes in a hierarchy transitively extend Object, but only the root does it directly. Transitively because all subclasses inherit all the traits of their parents, including their parent classes and implemented interfaces.
I know that a class can implement more than one interface, but is it possible to extend more than one class? For example I want my class to extend both TransformGroup and a class I created. Is this possible in Java? Both statements class X extends TransformGroup extends Y and class X extends TransformGroup, Y receive an error. And if it is not possible, why? TransformGroup extends Group but I guess it also extends Node since it inherits fields from Node and it can be passed where a Node object is required. Also, like all classes in Java, they extend Object class. So why wouldn't it be possible to extend with more than one class?
TransformGroup inheritance
So, if that is possible, what is the proper way to do it? And if not, why and how should I solve the problem?
In Java multiple inheritance is not permitted. It was excluded from the language as a design decision, primarily to avoid circular dependencies.
Scenario1: As you have learned the following is not possible in Java:
public class Dog extends Animal, Canine{
}
Scenario 2: However the following is possible:
public class Canine extends Animal{
}
public class Dog extends Canine{
}
The difference in these two approaches is that in the second approach there is a clearly defined parent or super class, while in the first approach the super class is ambiguous.
Consider if both Animal and Canine had a method drink(). Under the first scenario which parent method would be called if we called Dog.drink()? Under the second scenario, we know calling Dog.drink() would call the Canine classes drink method as long as Dog had not overridden it.
No it is not possible in java (Maybe in java 8 it will be avilable). Except the case when you extend in a tree.
For example:
class A
class B extends A
class C extends B
In Java multiple inheritance is not permitted for implementations (classes) only for interfaces:
interface A extends B, C
E.g. MouseInputListener extends MouseListener and MouseMotionListener
And, of course, a class can implement several interfaces:
class X implements A, F
Multiple inheritance is not possible with class, you can achieve it with the help of interface but not with class. It is by design of java language. Look a comment by James gosling.
by James Gosling in February 1995 gives an idea on why multiple
inheritance is not supported in Java.
JAVA omits many rarely used, poorly understood, confusing features of
C++ that in our experience bring more grief than beneļ¬t. This
primarily consists of operator overloading (although it does have
method overloading), multiple inheritance, and extensive automatic
coercions.
There is no concept of multiple inheritance in Java. Only multiple interfaces can be implemented.
Assume B and C are overriding inherited method and their own implementation. Now D inherits both B & C using multiple inheritance. D should inherit the overridden method.The Question is which overridden method will be used? Will it be from B or C? Here we have an ambiguity. To exclude such situation multiple inheritance was not used in Java.
Java didn't provide multiple inheritance.
When you say A extends B then it means that A extends B and B extends Object.
It doesn't mean A extends B, Object.
class A extends Object
class B extends A
java can not support multiple inheritence.but u can do this in this way
class X
{
}
class Y extends X
{
}
class Z extends Y{
}
Most of the answers given seem to assume that all the classes we are looking to inherit from are defined by us.
But what if one of the classes is not defined by us, i.e. we cannot change what one of those classes inherits from and therefore cannot make use of the accepted answer, what happens then?
Well the answer depends on if we have at least one of the classes having been defined by us. i.e. there exists a class A among the list of classes we would like to inherit from, where A is created by us.
In addition to the already accepted answer, I propose 3 more instances of this multiple inheritance problem and possible solutions to each.
Inheritance type 1
Ok say you want a class C to extend classes, A and B, where B is a class defined somewhere else, but A is defined by us. What we can do with this is to turn A into an interface then, class C can implement A while extending B.
class A {}
class B {} // Some external class
class C {}
Turns into
interface A {}
class AImpl implements A {}
class B {} // Some external class
class C extends B implements A
Inheritance type 2
Now say you have more than two classes to inherit from, well the same idea still holds - all but one of the classes has to be defined by us. So say we want class A to inherit from the following classes, B, C, ... X where X is a class which is external to us, i.e. defined somewhere else. We apply the same idea of turning all the other classes but the last into an interface then we can have:
interface B {}
class BImpl implements B {}
interface C {}
class CImpl implements C {}
...
class X {}
class A extends X implements B, C, ...
Inheritance type 3
Finally, there is also the case where you have just a bunch of classes to inherit from, but none of them are defined by you. This is a bit trickier, but it is doable by making use of delegation. Delegation allows a class A to pretend to be some other class B but any calls on A to some public method defined in B, actually delegates that call to an object of type B and the result is returned. This makes class A what I would call a Fat class
How does this help?
Well it's simple. You create an interface which specifies the public methods within the external classes which you would like to make use of, as well as methods within the new class you are creating, then you have your new class implement that interface. That may have sounded confusing, so let me explain better.
Initially we have the following external classes B, C, D, ..., X, and we want our new class A to inherit from all those classes.
class B {
public void foo() {}
}
class C {
public void bar() {}
}
class D {
public void fooFoo() {}
}
...
class X {
public String fooBar() {}
}
Next we create an interface A which exposes the public methods that were previously in class A as well as the public methods from the above classes
interface A {
void doSomething(); // previously defined in A
String fooBar(); // from class X
void fooFoo(); // from class D
void bar(); // from class C
void foo(); // from class B
}
Finally, we create a class AImpl which implements the interface A.
class AImpl implements A {
// It needs instances of the other classes, so those should be
// part of the constructor
public AImpl(B b, C c, D d, X x) {}
... // define the methods within the interface
}
And there you have it! This is sort of pseudo-inheritance because an object of type A is not a strict descendant of any of the external classes we started with but rather exposes an interface which defines the same methods as in those classes.
You might ask, why we didn't just create a class that defines the methods we would like to make use of, rather than defining an interface. i.e. why didn't we just have a class A which contains the public methods from the classes we would like to inherit from? This is done in order to reduce coupling. We don't want to have classes that use A to have to depend too much on class A (because classes tend to change a lot), but rather to rely on the promise given within the interface A.
Java does not allow extending multiple classes.
Let's assume C class is extending A and B classes. Then if suppose A and B classes have method with same name(Ex: method1()). Consider the code:
C obj1 = new C();
obj1.method1(); - here JVM will not understand to which method it need to access. Because both A and B classes have this method. So we are putting JVM in dilemma, so that is the reason why multiple inheritance is removed from Java. And as said implementing multiple classes will resolve this issue.
Hope this has helped.
Hello please note like real work.
Children can not have two mother
So in java, subclass can not have two parent class.
Is java.lang.Object superclass of all the custom class/objects inherited implicitly? I thought java didn't support multiple inheritance. The reason I ask is if I already inherit from another class in my custom class and again java is forcing implicit inheritance of java.lang.Object on top of it, is it not multiple inheritance?
Also, is java.lang.class Class also the superclass for all custom classes/Objects? If not, how in java reflections we can get the type of class for any class passed or call isInstance on any object?
Every class without an explicit superclass inherits from java.lang.Object and every other class inherits from it indirectly because when you go up the inheritance tree, you will finally end at a class without an explicit superclass and then at Object.
java.lang.Class is the superclass of all class objects (not of all objects!), for example of String.class.
Is java.lang.Object superclass of all
the custom class/objects inherited
implicitly?
Minor correction: regarding the following expression:
superclass of all the custom
class/objects
A class A is a superclass of another class B. Objects or instances of B do not have A as their superclass (since they are objects/object instances, not classes themselves.) The most appropriate description is that these objects are instances of class B, which has A as its superclass.
Now, to your question on java.lang.Object. It is the superclass of everything that can be instantiated by the java runtime. That includes both:
classes you write (custom classes), as well as
classes provided by the Java language itself.
I thought java didn't support multiple
inheritance.
It doesn't. It only support single class (or implementation) inheritance (in conjunction with multiple interface (or type) inheritance.
You are confusing inheritance with class hierarchy. Pls see further below.
The reason I ask is if I already
inherit from another class in my
custom class and again java is forcing
implicit inheritance of
java.lang.Object on top of it,
And that's fine with multiple inheritance. Say you have a class B that you wrote inheriting from a class already provided by Java (say class A). So there is a linear, transitive relation as follows:
java.lang.Object > A > B
Where > stands for immediate parent of. Any class inheriting from Object can only have one and only one immediate parent. At no point you'll have a class C for which the following constrain for any two classes A and B does not hold:
forAll A, B { A > B -> forAll C { C >
B <-> C == A } }
Meaning, for all classes A and B such that A is an immediate parent of B, then for all classes C, C can only be an immediate parent of B *if and only if C is itself A.
With single inheritance you can have (theoretically) an infinite inheritance chain A > B > C > ... so long as every class in the chain is preceeded by one and only one immediate parent. As a useful analogy, this resemble the predecessor relationship in natural numbers (0 preceedes 1 preceedes 2 which preceedes 3 ...).
Disclaimer: This is not stuff that you use in day-to-day programming life activities. However, knowing precisely what these things mean under the hood will tremendously help you get through object orientation.
is it not multiple inheritance?
No (see above.) As opposed to single inheritance - explained above - in multiple inheritance you can have multiple immediate parents (as seen in C++).
As we noticed in the definitions above, the transitive inheritance relation '>' is from one class to another. But with multiple inheritance, the relation is from a set of superclasses {A} to a single class {B}:
{A} > B -> forAll a {a in A <-> a > B}
And in C++ where you can have classes without parents, then the set {A} can be the null set. In java, you also have multiple inheritance, but limited to interfaces (or types.)
Also, is java.lang.class Class also
the superclass for all custom
classes/Objects?
No. It will help your learning if you take a visit to the Javadoc manuals which are available online. Look it up. Really.
If not, how in java reflections we can
get the type of class for any class
passed or call isInstance on any
object?
Because instances of java.lang.Class (and all classes used by java reflections) are meta-data descriptors for other classes. This has nothing to do with inheritance. What you are referring to here is known as meta-programming.
Furthermore, java.lang.Class is a final class; ergo, it cannot be the superclass of anything.
The function of java.lang.Class is to be a meta-data provider/descriptor for all instances and subclasses of java.lang.Object (including java.lang.Class itself.) The class field associated to each class (.ie. String.class) is a static, class-level field describing the meta-data associated to that class.
The meta-data contained/described by java.lang.Class contains meta-data accessor objects for methods, constructors and fields. Again, this has nothing to do with inheritance.
Inheritance =/= meta-programming.
Hope it helps.
Everything is an Object, that said you could see the structure as this:
Object
Animal
Cat
and not as this:
Object Animal
Cat
Where Cat extends both, it's not like this last example, but it's Cat that extends Animal which extends Object.
Multiple inheritance means that one class has multiple direct predecessors. If A inherits from B, and B inherits from C, this is not multiple inheritance.
I don't understand the second question ("java.lang.class Class"); you might want to rephrase that to clarify.
Object is the superclass of every other class. When your Child class inherits from your Parent class, it is not the child of Object, but it is still a descendant, because its parent is a descendant of Object.
So if you don't specify a superclass/parent, it will automatically be Object. If you do specify a parent, then Object will still be a superclass, because it is by definition a superclass of the parent class.
Class is not a superclass of each class, but the Object class specifies a means to get each class's Class with the getClass method.
The custom class that you inherit from itself inherits directly or implicitly from Object, so you indirectly inherit from Object. The chain goes YourObject -> MiddleObject -> java.lang.Object. No multiple inheritance necessary.
Multiple inheritance is when you directly inherit from two unrelated classes. For example, if you have a class PoliceDog that inherits directly from both Canine and PoliceOfficer, that would be multiple inheritence.
In that case, it's not multiple inheritence but multi-level
inheritance.
For example, let's say you have a class say, Class Animal,
this class will be extending Object class, by default and extends no
other class.
Also let's assume, you have a class which extends the
Class Animal, say Class Lion. In this case, the Class Lion will not be
directly inheriting the Object Class but since it inherits Class
Animal which inherits Object class, it also indirectly inherits
it.
This question already has answers here:
Java : If A extends B and B extends Object, is that multiple inheritance
(11 answers)
Closed 8 years ago.
Class Object is the root of class hierarchy. Every class has Object as a superclass. So, if I am extending a API class, will it be like, multiple inheritance? Obviously, Java doesn't support multiple inheritance. How does it then work?
Superclass is not the same thing as parent class. You can only have one mother, but you have a much larger number of female ancestors.
Java doesn't support multiple inheritance, as everyone else explained.
But you can (kind of) have multiple inheritance when you implement multiple interfaces:
interface Moveable {
void relocate(Coordinate position);
Coordinate getCurrentPos();
}
interface Tradeable {
void sell(BigInteger amount);
void buy(BigInteger amount);
}
interface Crashable {
void crash();
}
class Vehicle implements Moveable, Tradeable, Crashable {
}
Now Vehicle should all methods from the interfaces it implements.
No, Object will just be the eventual parent class of any class you create
Multiple inheritence would mean you could write a class that extends String and Integer for example, and gains the properties of each. This cannot be done with Java. You probably want to look at the Delegate pattern if this is the sort of thing you want to do
no, its just inheritance, business as usual
grandparent
parent
child
the child only has one parent,
and the parent has a grandparent (doesnt make logical sense, but whatever :)
multiple inheritance would be when you inherit from two different classes does not need to have anying do with each other
donkey car
donkeycar
(as you already noted, its not possible in java)
The super class of your object also has a super class and so on.
All objects form a tree with java.lang.Object as it's root node.
No.
The multiple inheritance mean that You inherit for example from two classes
class A {}
class B {}
class C extends A, B {}
and this is not possible in Java.
What You can do is
class A {}
class B extends A {}
class C extends B {}
So You have more then one super class but only one parent.
My understanding of it it that multiple inheritance works horizontally (multiple parent superclasses inherited directly into one subclass) rather than vertically (parents of parents), thinking of the inheritance tree.
As you say, only the vertical kind is allowed in Java.
Inheritance is transitive. You extend an API class, and that API class itself extends Object. So you're indirectly extending Object. Shorter, if A extends B and B extends C, then A extends C.
This is not multiple inheritance. The 'inheritance chain', if you will, can be as long as you want it to be. But in the end, everything has Object at the end of it.
Real multiple inheritance would be extending from two unrelated classes at once. You cannot do this in Java.