Related
I just had an interview, and I was asked a question.
Interviewer - Does Java support multiple inheritance?
Me - No
Interviewer - Each class in Java extends class Object (except class Object) and if we externally extend one class like
Class A extends B{
// some code here
}
then you can say that class A extend class B and class Object, which means it is multiple inheritance. So how can you say Java does not support multiple inheritance?
Me - Actually class B extends class Object, so when you extend class B in class A then class A extends class Object indirectly. This is multi-level inheritance, not multiple inheritance.
But my answer did not satisfy him.
Is my answer correct? Or where am I wrong?
What actually happens internally?
My answer is correct?
Yes, mostly, and certainly in the context you describe. This is not multiple inheritance:
It's what you said it is, single inheritance with multiple levels.
This is multiple inheritance: Inheriting from two or more bases that don't have any "is a" relationship with each other; that would be inheriting from unrelated lines, or from lines that had previously diverged (in Java, since Object is always a base, it would be the latter):
(Image credits: http://yuml.me in "scruffy" mode)
Internally What happens actually?
Just what you said: There are multiple levels. When the compiler is resolving a member on an instance:
obj.member
...it looks to see if the type of obj (which in this case is a class, say ClassB) has member, either because it provides it directly or it has it through inheritance. At runtime, the JVM uses the member the object actually has.
The reason I said "mostly" above is that Java has interfaces, and as of Java 8 it has "default methods" on interfaces. This complicates things a bit, but your answer about levels is correct in the context of what you described the interviewer saying about Object, ClassA, and ClassB.
Interfaces have always made it possible, in Java, for something to have an "is a" relationship with two different types: A class type it inherits from, and any of several interface types it implements. Interfaces without default methods aren't multiple inheritance in a practical way (the class has to provide the implementation), but they did make it possible for a class to have multiple "is a" relationships from unrelated type trees. (I'm not an academic, it's possible an academic would argue that they provide multiple inheritance in an academic way.)
With Java 8, interfaces can provide default implementations of the methods they define, which really blurs the lines even at the practical level. Let's look at that a bit more deeply:
Say we have ClassA:
class ClassA {
void doSomething() {
// Code here
}
}
and Interface1:
interface Interface1 {
default void doSomethingElse() { // Requires Java 8
// Code here
}
}
and finally ClassB:
class ClassB extends ClassA implements Interface1 {
}
ClassB inherits the implementation of doSomething from ClassA. But it also gets the "default" version of doSomethingElse from Interface1. We didn't implement it in ClassB, but ClassB isn't abstract: It really has doSomethingElse. It gets it from the interface. I used the word "gets" rather than "inherits" there, but this looks a lot like inheriting the default method.
This is basically multiple-inheritance "light" (as in "light beer"). It does an end-run around the thornier problems with true multiple inheritance, like:
What should the type of super be? (Java 8's answer: ClassA)
What order do you run constructors in? (Java 8's answer: Single-lineage constructor chaining, interfaces don't have constructors.)
Do you run constructors that you inherit more than once, more than once? (Java 8's answer: You can't inherit constructors more than once, interfaces don't have them.)
What happens if you inherit multiple methods with the same signature? (Java 8's answer: If one of them is from the base class, that's the one that's used; a base class's implementation can override the default method of multiple interfaces. If you have multiple default methods with the same signature from different interfaces at compile-time, it's a compile-time error. If an interface has been changed without the class being recompiled and the situation arises at runtime, it's a runtime IncompatibleClassChangeError exception listing the conflicting default methods.)
you are correct
First of all, Object class is the super/base/parent class of every class including user-defined classes.
So even if we don't mention it explicitly, the user-defined classes extends Object class by default.
its like
class A
class B extends A
but compiler read it as
class A extends Object
class B extends A
proved
for more detail check this java documentation for inheritance
My answer is correct?
You are absolutely correct in saying that it is multi-level inheritance and not multiple inheritance.
Only the root of the hierarchy is Object, all classes don't individually extend Object.
A counter to the interviewer:
If all classes extend Object, then how many times constructor of Object will be called on A a = new A();
The answer is only once, and that will be for the root of the hierarchy.
Multiple inheritance and class Object
Yes, you are correct... as many others have pointed out. I just wanted to say that interviews are not only about technical knowledge, it is also about sticking to your guns. Some interviewers will question your answer, not because they want to know if you are sure of your convictions but also to test how well you can teach others and how well you handle an authoritative figure.
For the first point, if you can't teach others then you can't be a mentor. Nowadays it is crucial to hire someone who can coach junior developers.... because it makes sense economically.
For the second point, because they don't want you changing technical aspects just because your boss asked you to. If your boss asks you to remove all indexes from the database because they take up too much space, would you do it? Would you try to convince your boss otherwise? How?
Does java support multiple inheritance?
Yes for interfaces but not for classes.
The class and interface can implements many interfaces but extends only one class
Your answer is correct !
class Object //for illustration purpose
{
}
class B
{
}
class A extends B
{
}
When you create an object of class A, constructor chaining happens.
i.e. the constructor of class A calls super() implicitly and hence the constructor of class B is invoked, which then calls its super class implicitly which is the Object class.
In java, a class extends only a single class because the constructor of that class only call one super class constructor. This is not true in case of Interfaces since they do not have constructors.
Also when an object of class A is created, and assume that you have defined the constructors of both classes A and B, then constructor of class B is executed first and then the constructor of class A.
Your answer is perfectly alright. You can explain interms of multilevel inheritance support from Object class in java
Your answer is right, because java doesn't support multiple inheritance from classes. Java supports multiple inheritance from interfaces, and there is no any other inheritance. But you can use composition of classes, but that's another story.
What a dumb question.
Of course Java doesn't support multiple inheritance, and interfaces are not inherited.
Inheritance only happens via "extends", not via "implements". When you define a class implements several interfaces you are not saying it will be an extension of those interfaces, but it will have the same behavior, and behavior (at least in Java), doesn't define inheritance.
For Java to support multiple inheritance, it would need to support something like
public class MI extends Object, MyOtherClass
Which Java can't.
Well, maybe I wouldn't get the job for calling the interviewer's question dumb :)
Your answer is absolutely correct.
These types of questions asked just to check whether a candidate is conceptually strong or not.
Well the simplest and precise answer to this question is here:
"Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class, Object. Such a class is said to be descended from all the classes in the inheritance chain stretching back to Object."
Please refer this link
https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
The answer you gave is correct. The interviewer was wrong:
Internal process
if suppose Class A Doesn't extends any other class
then ---> Class B extends java.lang.Object
then ---> Class A extends B
then class A also inherited the property of java 'Object' class...
so,Java doesn't support multiple inheritance.
If you want to verify this process just generate 'javadoc' for your class A and verify the results.
I'm new to Java programming and right now, I am trying to understand OOP concepts (inheritance, polymorphisms, etc.).
I know that, when a subclass extends a superclass (abstract or not), subclass constructor calls the constructor of that superclass first (super()).
My questions are:
1) Is it the same case for Interfaces? I've read some articles saying that interfaces don't have constructors, so how exactly are they being extended?
2) How come multiple inheritance is not supported in Java but an interface can "extend" multiple other interfaces?
Thanks in advance.
1) Is it the same case for Interfaces? I've read some articles saying that interfaces don't have constructors, so how exactly are they being extended?
Yes, there is no constructor in an interface, you will have to define a concrete class(that implements that interface) to create an object of that interface type.
Example: you can check the profile of java.io.Serializable using javap java.io.Serializable which is:
public interface java.io.Serializable {
}
which says there is no constructor.
2) How come multiple inheritance is not supported in Java but an interface can "extend" multiple other interfaces?
Yes you can extend multiple interfaces, this is because, if two interface contains abstract method with same signature, this will not be an ambiguity to the compiler. But this is not with the case with class, if you will try to extend two classes that have method with same signature then it will be an ambiguity to the compiler for which method to call as method declaration might be different in different class.
Yes, you can do it. An interface can extends multiple interfaces.
interface Maininterface extends inter1, inter2, inter3{
// methods
}
Not only interfaces,A single class can also implements multiple interface. Then obviously a doubt raises, what if two methods have an same method name.
There is a tricky point:
interface A
{
void test();
}
interface B
{
void test();
}
class C implements A, B
{
#Override
public void test() {
}
}
Then single implementation works for both :)
1) Is it the same case for Interfaces?
Not really. Constructors for an interface don't really make sense, as constructors define some initial state, but interfaces don't have state. So constructors aren't being called.
I've read some articles saying that interfaces don't have constructors, so how exactly are they being extended?
You should think of extending an interface as more extending a type -- that is, expanding the defined behaviors of something. It's like taking a contract and adding some clauses onto the end -- you're saying "In addition to the methods defined in the superinterface, I want classes implementing this interface to also implement______"
Extending a class is somewhat similar, as you also extend a type, but the thing is that extending a class should be considered to be adding additional state/implementation to a type. Because of this, superclass constructors should be called to make sure that all the state associated with the superclass definitions is properly initialized.
2) How come multiple inheritance is not supported in Java but an interface can "extend" multiple other interfaces?
You have to be careful here, as there isn't just one kind of multiple inheritance. Java does support multiple inheritance of types, which is why you can implement multiple interfaces, which define types. What Java doesn't support is multiple inheritance of state (and multiple inheritance of implementation wasn't allowed until Java 8. See note below). This is why you can only extend 1 class -- because classes define state.
Thus, because you're allowed to inherit multiple types, extending multiple interfaces is perfectly OK for a given interface. It's like taking one contract and stapling several other contracts to the back of it. As long as the implementing class follows the entire thing, your program should compile.
Note: As of Java 8, you can now inherit multiple implementations, through default methods in interfaces. In the case of a conflict, the programmer must explicitly implement the method in question.
First of all try to clear the concept of inheritance . The basic concept behind Inheritance is to inheriting (getting ) all the property(variables and methods)(considering access modifier ) of parent class with our rewriting them in the child class.
Suppose we have a Class A,
class A{
public void doA()
{
}
}
now if class B extends A(mark the literal meaning of extends) it will get the method doA(), inherently. If you look at the literal part actually B extends A it seems B is an extended version of A.
Now Come to the Interface part. If I have a interface InA
interface InA{
doInA();
}
and i try to inherit it in class B i need to implement (mark the literal again) it. So i will get the method doInA() it B but i need to give it a body.
In case of of Interface to Interface, Now as you have used two key word for inheritance. If i ask you that an interface InB will inherit interface InA what key work will you chose among extends and implements? doesn't the extends sounds more logical. Because InB implementing nothing its just getting bigger and it will be an extended version of InA.
Now Lets answer you two key question:
1.Is it the same case for Interfaces?
Yes and No. actually the constructor of parent only be called when the constructor of child is called. So as you never can call the constructor of child Interface the constructor of parent interface will never be called. Its doesn't call the parent constructor but still it reserve the technique of constructor calling .
2) How come multiple inheritance is not supported in Java but an interface can "extend" multiple other interfaces?
Have a look at this Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?
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 read that interfaces do not have a constructors, which means it will not call super() of its super class. I also read that each and every class in Java is a subclass of Object
What about an interface, is it subclass of Object? Why?
No it's not. An interface cannot be instantiated to form an object, it is not a class.
An interface is a named collection of method definitions (without implementations). An interface can also include constant declarations.
Interface and class have some basic difference and one of them is do not have a constructors. Actually interface does not made for it and you cannot instantiate interface but there is way you can still instantiate interface.
interface Interface{
abstract String fun();
}
Interface interfc=new Interface() {
#Override
public String fun() {
return super.toString();
}
};
Type type=interfc.getClass();
Here interface has been instantiated as anonymous class.But still you cannot place constructor here according to java language specification. But still you can use super class Which will be immediately super class of this anonymous class.
An anonymous class cannot have an explicitly declared constructor.
And there is alternative solution of this that is using final variable in super class.
No interface is a subclass of Object class, since interface cannot extend a class whether implicit or explicit.
Reason for constructor is to create an instance, since interface cannot be instantiated as they don't provide any functionality they are just a contract only class can be instantiated hence they have constructor.
While some people suggest thinking of interfaces as "can-do" rather than "is-a" relationships, I think it's more helpful to think of them "is a __er" or "is a __able thing". To use a real-world analogy, a book (dead-tree edition), a bound paper magazine, a newspaper, a promotional advertising flyer, a sign, and a scrap of paper with some words written on it, are all "readable things". If someone were to show another person a book and ask "Is this a readable thing", the answer would be that it is. On the other hand, if someone were to show another person a book and ask "What is this?" the response would not be "A readable thing", but more likely "A book", or perhaps "A hardcover fifth-printing copy of the second U.S. edition of the novel 'Great Expectations' by Charles Dickens". Any type of "readable thing" has some identity beyond merely being a "readable thing".
Likewise with Java interfaces. An object may implement an arbitrary number of interfaces, but every object must have a type in addition to the set of interfaces it supports. Note that it is possible to define a method which will return a new object of unknown type that implements an interface; that would be equivalent to asking someone, "Please get me something to read" without specifying what type of object was desired. Such a method could select a type of object to return, and give the caller one which is "readable". Constructors, however, unlike general methods, require the caller to specify precisely what type of object is desired. Merely specifying that an object is "readable" would not be a sufficient specification.
No interface can not have constructor. Because interface support multiple inheritance. That means if a class inherit two interface then due to constructor chaining there will be ambiguity which constructor will be called from class constructor.
I'm reading a book about data structures in java, and it's talking about iterators now. I saw the following code and it seems odd to me. In the following code, AbstractIterator is an abstract class that implements Iterator<E>, UniqueFilteris a subclass of AbstractIterator that is not abstract, and data is a Vector. I guess I don't understand how in the first line you can take the output of the Vector.iterator() method and cast that into an abstract class. After line 1, is dataIterator not an instantiated instance of an abstract class?
AbstractIterator<String> dataIterator =
(AbstractIterator<String>)data.iterator();
AbstractIterator<String> ui = new UniqueFilter(dataIterator);
The problem is that there are two different types we are talking about. The (run time) type of an object and the (compile time) type of a reference.
dataIterator is a reference of an abstract type - that's ok.
data.iterator() returns a reference to an object whose type is not clear from the example, but apparently it's a concrete type which inherits from AbstractIterator<String> - that's ok
You can always assign a reference to object of type B to a reference to object of type A if B is a child of A, even if A is abstract (or interface). You actually don't need the cast.
So after line one dataIterator is still a reference of type AbstractIterator<String>, but it's a reference to an object of a concrete type which implements AbstractIterator<String>.
Remember, in JAVA all the object variables are actually references.
UniqueFilter is irrelevant for this question, btw.
Inheritance means IS-A. If a Child inherits from a Parent, then Child IS-A Parent and can be used in any situation where a Parent is called for.
Since UniqueFilter IS-A AbstractIterator, this means you can cast it just as your code shows.
Why would you not believe the JVM?
After line 1, is dataIterator not an instantiated instance of an abstract class?
It is an instance of a UniqueFilter which also makes it an AbstractIterator by inheritance. Attempting to "instantiate and instance of an abstract class" means attempting to call the abstract class' constructor, that's what's not allowed, and that's what's not happening here.
Abstract Class is a class that cannot be instantiated. Often it will include one or more methods that are also declared abstract and must be implemented by subclasses for the subclass to be concrete (opposite of abstract), and therefore able to be instantiated.
UniqueFilter is a subclass of AbstractIterator ( an abstract class). Since this is a IS-A kind of relationship, you cannot declare an instance of abstract class.
If you want to create an instance for abstract class, first you create a concrete subclass and create an instance for that and use it.
From what you've described it looks like there's an assumption that can be made that has been overlooked; that the implementing type returned by data.iterator() here is a subclass of AbstractIterator<String>.
If this assumption can be made, then the first statement becomes obvious as an object can be legally type cast to any object up the inheritance hierarchy, in this case an AbstractIterator<String>.
In this case dataIterator is NOT an instantiated instance of an abstract class; its not being instantiated here (i.e new AbstractIterator<String(...)), its just a reference to the instantiated instance returned by Vector.iterator() with the type being that of a superclass of the actual returned type, which happens to be an abstract class.
HeadofState is an abstract (by the English meaning of the word abstract) term.
There is no country in the world where the official title of its head-of-state is Head-of-State.
A head-of-state, even though abstract in language and existence, is a super class or super category of titles like sultan, president, premier, prime minister, beloved father, etc.
So, even though the existence of head-of-state cannot be instantiated in its abstract form, you can instantiate (by democratic means, hereditary or by coup) a president, a prime minister, or any honcho-what-nots.
So say, a prime minister has been instantiated, it can then be equated to its abstract parent terminology of "Head-of-State".
So even though an abstract class cannot be instantiated, an implementation of that abstract class can be instantiated. That is what factories can do. Factories are a means to create instances of abstract classes.
Just like abstract classes, interfaces cannot be instantiated but must be implemented. Abstract classes are partially implemented, whereas interfaces are totally unimplemented by themselves. Abstract classes and interfaces depends on derivative classes to complete their existence. Of course, the obsessive OO-purist's technical terminology would clarify that abstract classes are "extended" and interfaces are "inherited".
For example, HttpServletRequest is an interface. You cannot instanstiate it directly. When your JSP grabs its http servlet request, it works the same whether you are in Jetty or Tomcat. However, if you inspect carefully, the actual class instantiated by the HttpServletRequest factory in Jetty is different from that created in Tomcat. But, since both of them implement HttpServletRequest, those instances can simply be equated to a variable whose type is HttpServletRequest.
You should read up on abstract classes vs interfaces and how interfaces are concocted to allow pseudo-multiple inheritance in Java. Once you understand the role of interfaces, you would then understand abstract classes. In the realm of object-oriented flame wars, some people think that Interfaces was a brilliant break-thro in multiple inheritance. Some people think interfaces have nothing to do with multiple inheritances. In my own less than humble opinion, interfaces are a poor and failed attempt at socialist's paternalistic indulgence to prevent me from getting into trouble that presumes that I don't know how to take care of myself.