Related
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.
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 know following cyclic inheritance hierarchy is not allowed in Java. Compiler throws an error, but what I'm really interested is knowing the exact reason for the compilation failure.
class A extends B{}
class B extends C{}
class C extends A{} // this will give you compile time error.
What is the thing due to which the compiler will throw an error, the moment I write the code class C extends A{}
Such relation is simply not possible. It defines an infinite recursive class. In order to define class C, you need class A, to define class A you need class B, and to define class B you need class C - and you are back to the starting point. This goes on infinitely so compiler can't do this and it also has no logical meaning.
Just look at the word extends, in Java a child class really extends its super class. It means child object is all of its super object plus some new members and some specified members.
So how can
A be an extension to B
B be an extension to C
C be an extension to A
?
We can say extension is an Order Relation so:
A extends B means A < B (and even not A <= B), and then in your case B < C, so it is obvious C can not be less than A.
There is simple a very practical problem (besides the logical problems which are explained in the other answers):
The classes must be initialized during instantiation. This is done in Java by initializing the superclass first. When you have a cycle the initialization code goes up the inheritance ladder and tries to initialize the superclass which is never reached...
Therefore for Java this must be forbidden.
We can reduce the problem to these statements since C IS-A B :
class A extends C{}
class C extends A{}
Obviously it is a conflict and thus the compiler gives that error.
Let's abstract out the concept of inheritance to family trees. Essentially, this is what they boil down to. I'll use the reverse mapping scheme here, so I'll work my way from C to A.
You inherit certain attributes from your mother.
Your mother inherits certain attributes from her father.
Your grandfather can be considered the highest in the inheritance chain.
In Java, this results in:
C inherits from B.
B inherits from A.
A is the highest object in your inheritance chain.
Taken to logical extremes, this would include multiple inheritance, a feature that is not supported in Java, yet can be mitigated through the use of interfaces.
What your inheritance scheme says is that the grandfather inherits directly from the grandchild, which makes no sense.
Cyclic Inheritance can have two examples:
1. Class A extends A { } :- This does not make any sense because members of class A are already present in class A then why to extend.
2. Class A extends B { } and Class B extends A { } :- In this case, members of both the classes can be written in one class then why to write two classes and extend each other.
Since above usecases are not-valid hence Java does not support Cyclic Inheritance.
I thought that I would add an as-of-yet unstated Java specific answer to this thread. In Java, every class must ultimately be derived from the Object class. That's why every object can be casted to an instance of Object without issue. To support this fact, the Java Inheritance Tutorial states:
Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.
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.
If cyclic inheritance dependencies are allowed, and because classes in Java must have exactly one direct superclass (see above), then instances of classes in any cyclic dependency chain (e.g. instances of your classes A, B, and C) could not be inherited from Object, which is not permitted. So none of these cyclic dependency objects could be treated as Objects. Thus, the compiler must forbid cyclic dependencies.
I am curious as to how the concept of "inheritance" takes place in the world of object oriented programming. Let me explain my dilemma (I came across this dilemma while studying Java but I hope that my question is generic in nature) :
Suppose there is a class A and a class B. Class A "inherits" Class B. What does this actually mean? Does the compiler make a "new" class, which is THEN instantiated into an object which contains the elements of both the classes A and B behind the scenes? If that's the case, then how are the access restrictions implemented according to the access specifiers?
For a moment, I wondered if it happens in the following manner :
An object of class A is created and then an object of class B is created. Java then somehow "link" the members of A to the members of B and make it appear as if they belonged to the same class and it does that according to the access specifiers.
But then, it occurred to me that there is a fault with this theory. Suppose two different classes, B and C are inheriting class A. Then, if we are going to make objects of class B and class C, then they'll have their OWN copies of the elements of class A. So this theory fails too.
I was just trying to explain the confusion about inheritance that I have in my mind. It's giving me headache. Please help.
EDIT : This is a link to a discussion related to my question which i found on this site.
Do subclasses inherit private fields?
I may fail, but I'm going to take a stab at an explanation on this for you.
In honesty, I think you may be making what is really a very classic mistake in how you conceive object programming - and that's making the distinction between objects and classes. Object creation in virtually any object-oriented language is one of construction based on a class definition. From your question, it sounds as though you are mentally modeling an OO language in general and object inheritance in particular as aggregating discrete objects, where in reality the objects are being defined in terms of aggregated class definitions.
public class A
{
public A();
}
public class B:A
{
public B();
}
public class C:B
{
public C();
}
In your A->B->C model, C's definition is in terms of its own unique properties plus all the members of its immediate ancestor, B, which, in turn, is defined in terms of its own unique properties plus all the members of its immediate ancestor, A. The process of creating the object is still a unique and discrete event, and the object, despite its multi-layered heritage, is still only one object at instantiation time.
Regarding the visibility of certain members: When a class author designs and builds a class, he makes certain decisions about what he makes available in two distinct perspectives: that which is exposed to consumers of the class, and that which is exposed or available to subclasses. Members and fields declared private are every bit a part of descendant classes, even if they are "contractually" forbidden to be accessed by subclasses. You could make a crude analogy that a TV has a "public" interface of an on/off button, volume control, and color controls, but has "internal" controls not intended for the consumer such as the internal electronic components, or the power supply. They're still very much there even though they are not "visible" or "available" to consumers or subclasses.
Now, that said, there are constructs in most OO languages that reflect the properties you describe - multiple objects - and that involve a design pattern known as Composition (or, sometimes, Aggregation. This is where a class isn't derived from an ancestor class - typically because the class is declared "sealed" (C#) or "final" (Java) (or other designation that prohibits inheritance). That forces a developer interested in using the class to make it a member of another class, such that when the an object of the class is instantiated, you DO have discrete objects of both classes.
You might have the following:
public final class InterestingThing
{
//definitions
public InterestingThing()
}
public final class MyThing
{
InterestingThing _interestingThing = new InterestingThing();
public MyThing()
}
This is very much the kind of scenario you were describing in your original question, in which the creation of MyThing implies the distinct creation of an InterestingThing. Keep in mind, too this structure is generally forced by the design and definition of the original class of interest.
Ultimately, objects are defined by their classes, and multiply-inherited classes are still just a class, but in a refined, hopefully increasingly robust, hierarchy based on good, incremental object design.
I hope, in some way, this explanation helps to answer your question.
Class A "inherits" Class B. What does this actually mean?
If class A extends class B, it inherits all members (fields and methods) of B, i.e. class A will have these members even through they are not declared in the body of class A.
Whether class A is permitted to access a particular member is an unrelated matter.
An object of class A is created and then an object of class B is created. Java then somehow "link" the members of A to the members of B and make it appear as if they belonged to the same class and it does that according to the access specifiers.
No. A single object of class A is created. That object just happens to have all inherited members, too. For instance, if you have:
class B {
private int x;
}
class A extends B {
private int y;
}
The runtime will store, for every object of class A, the value of x and the value of y.
That code in class A does not access the value of x is enforced by verifying that the source code of A does not use the name x upon compilation, and by verifying that the bytecode of A does not refer to the field x upon loading the class at runtime. Put differently, access modifiers are independent of memory layout.
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.