Multiple inheritance in Java or not? [closed] - java

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
It is said, that Java language support single inheritance only.
However how is it possible to inherit from Object and from any other class at the same time? Isn't that a multiple inheritance.
Secondly, what for do we need to inherit all 11 Object methods? I could hardly imagine why do I need it them in I/O e.g.
Finally JDK 8 is going to offer us default methods realization in interfaces and if which would probably cause multiple inheritance in Java.
What if interface A provides method a() with default realization and interface B provides also a() method with another default realization and our custom class C implements both interfaces and rely on default realization - wouldn't that be Diamond of Death ?

However how is it possible to inherit from Object and from any other
class at the same time? Isn't that a multiple inheritance.
No this is not what happens. Not all classes directly extend from Object class. But only the class at the top level of inheritance hierarchy extends from Object class(implicitly). Rest of the classes lower in the hierarchy, extends from the Object class through the super classes. And, this is what we call multi-level inheritance.
So, consider the below hierarchy: -
class A { }
class B extends A { }
In the above case, class A is equivalent to class A extends Object.
Secondly, what for do we need to inherit all 11 Object methods? I
could hardly imagine why do I need it them in I/O
I suspect you meant override when you say inherit. You don't need to override any method of Object class. It's just on your requirement, whether to override any method or not. For e.g.: - You would often want to override equals() method, so as to write custom equality test for your instances. And in that case, you should also override the hashCode() method, to maintain the contract of equals() and hashCode().
Finally JDK 8 is going to offer us default methods realization in
interfaces and if which would probably cause multiple inheritance in
Java.
What if interface A provides method a() with default realization and
interface B provides also a() method with another default realization
and our custom class C implements both interfaces and rely on default
realization - wouldn't that be Diamond of Death ?
I can't comment on this concept, because I haven't read about this thing yet. Probably, I would update the answer sometime later.

However how is it possible to inherit from Object and from any other
class at the same time? Isn't that a multiple inheritance.
Unless otherwise specified, a class extends Object. That is, this:
class A { ... }
is equivalent to:
class A extends Object { ... }
Secondly, what for do we need to inherit all 11 Object methods? I
could hardly imagine why do I need it them in I/O e.g.
equals() and hashCode() are used in comparisons and hash tables.
notify() and wait() form the low-level basis of cross-thread communication.
getClass() is the starting point of all reflection code.
By putting them on Object, these can be used on every object in the JVM. You can get the hash code and the class of any object, you can check for equality between any two objects, you can monitor and notify any object.
What if interface A provides method a() with default realization and
interface B provides also a() method with another default realization
and our custom class C implements both interfaces and rely on default
realization - wouldn't that be Diamond of Death ?
As explained in another question here on SO (which is literally just one search for "jdk8 default methods" away):
To solve multiple inheritance issue a class implementing two
interfaces providing a default implementation for the same method name
and signature must provide an implementation of the method.
Thus, the class must provide its own implementation, possibly delegating to one of the default methods.

You are correct about "Diamond of Death" but ...
This is the situation where D implements interfaces C and B and both of those implement A. Further, there is a default method defined in two or more of those interfaces.
In Java 8 they defined a way that the two default method definitions are sorted out.
As I recall, if A and B both have a default method defined, then D uses B's version since it is lower in the class hierarchy.
If B and C both have the same default method defined then there is a conflict and D will need to implement the method itself though it can do so by calling back to the version implemented in either B or C (or it can have conditions and use both in different cases).
interface A { }
interface B implements A { void m() default {println("In A");} }
interface C implements A { void m() default {println("In B");} }
}
class D implements B, C {
public void m() { println("In D"); B.super.m(); }
}
But you can go to Oracle's pages about new features in Java 8 and read all about it. I got there by Googling "Java 8 new features". Found what I was thinking of at http://cr.openjdk.java.net/~briangoetz/lambda/Defender%20Methods%20v4.pdf

You inherit from a class, which inherits from object. Java does not allow you to inherit from two different class chains. However, the way around this is to use interfaces.

However how is it possible to inherit from Object and from any other
class at the same time?
You cannot do this, you heard wrong.
Secondly, what for do we need to inherit all 11 Object methods? I
could hardly imagine why do I need it them in I/O e.g.
Not sure what you're talking about here.
What if interface A provides method a() with default realization and
interface B provides also a() method with another default realization
and our custom class C implements both interfaces and rely on default
realization - wouldn't that be Diamond of Death ?
Don't know anything about JDK8, but you can already implement a method with the same name/type signature in two interfaces, which is probably illogical but Java allows it.

First- everything is an Object or a primitive in Java so you have no problems here. Object is the class on the top of the hierarchy.
At the moment you can apply multiple interfaces to Java already- then you write your realization. I would imagine that in Java 8- if you define your interface, then you have the realization. If not- then some default is used. If more than one default is defined (or the method is declared by more than one interface)- no default is used. It can be quite simple.

Related

#Override, with default methods in interfaces

I've been reading through some questions here on SO concerning the use of #Override in Java. (e.g. this one on override and this one on default methods, and obviously the documentations) However, I am still confused.
I was taught to always use and implement an interface when all behaviour in that interface needed to be used by a class. I get that. But as I was taught, you would do something like this (partially taken from the docs):
public interface TimeClient {
void setTime(int hour, int minute, int second);
}
Which is then implemented by a class.
public class TestSimpleTimeClient implements TimeClient {
public static void main(String[] args) {
}
#Override
public void setTime(int hour, int minute, int second) {
System.out.println(hour + " " + minute + " " +second);
}
}
The thing that bugs me is the implementation of the method in the interface. It doesn't do anything, it's only declared as a method that take arguments but doesn't do anything else. Then you take that method and Override it in a class that implements that interface.
I understand that this is a way to "force" classes to implement a method but I don't see how this is useful in some specific use cases.
Let's say I have an interface that's implemented by a couple of classes. I want most of these classes to share the same implementation of the method, but not all. The logical, and character-efficient way would be to have a way to say: these classes take the default method in the interface, but these classes override the default method. How would I go about doing that? Should the one that overrides the method only implement it, whereas the ones that simply use the default method as a whole extend it? And what if you only want this behaviour for a specific method in an interface?
The thing that bugs me is the implementation of the method in the interface. It doesn't do anything, it's only declared as a method that take arguments but doesn't do anything else.
That is not an "implementation of the method in the interface". That's just an interface method declaration. In programming, terminology matters. Interfaces tend to be devoid of any implementations. (Unless you are talking about the default interface methods of Java 8, but from the rest of your question it is unclear whether you are aware of their existence.)
I understand that this is a way to "force" classes to implement a class
A class cannot implement a class. A class extends a class. But a class implements an interface. In programming, terminology matters a lot.
It is not just a way to force classes to provide an implementation. It is also a way for callers to be able to invoke an interface method without having to know anything about the class that implements it.
but I don't see how this is useful in some specific use cases.
Well, take for example the Collection<T> interface, and the contains() method, which is implemented by a myriad of classes, among which ArrayList<T>, LinkedList<T>, HashSet<T>, BoundedBlockingQueue<T>, and so on, and so forth. Your code may look like this:
boolean hasPekingese( Collection<Animal> animals )
{
return animals.contains( AllOfMyAnimals.PEKINGESE );
}
Note how the hasPekingese() method does not have to know the exact class that is implementing Collection<Animal>. Which means that you may invoke hasPekingese() from a class which keeps its animals in an ArrayList<Animal>, and you may also invoke hasPekingese() from a class which keeps its animals in a BoundedBlockingQueue<Animal>. The method hasPekingese() does not know, and does not care.
Let's say I have an interface that's shared by a couple of classes.
It is unclear what you mean by "shared". Do you mean "implemented"? In programming, terminology is of paramount importance.
I want most of these classes to share the same implementation of the method, but not all. The logical, and character-efficient way would be to have a way to say: these classes take the default method in the interface, but these classes override the default method. How would I go about doing that?
There are many ways to go about that, the most common being to have some of these classes extend some common base class, which provides the common implementation of your method, so that the derived classes inherit this method, so they do not have to implement it. The rest of the classes do not extend that common base class, so each one of them has to provide its own implementations of that method.
Should the one that overrides the method only implement it, whereas the ones that simply use the default method as a whole extend it?
That's not clear. Also, please do not call it a "default method", because as of Java 8 "default method" is a term that has a very specific meaning, and although it is related to this discussion, it is different from the sense in which you are using it.
And what if you only want this behaviour for a specific method in an interface?
If a derived class wants the method to work differently, it may re-override it. Or, you may have two different base classes, one which implements the method in a certain way, and another which implements it differently, so half of your derived classes extend the first base class, while the other half of your derived classes extend the second base class.
Interfaces are like APIs. When some provider give you interface like List you don't think about if it is an ArrayList or other implementation, you just know what you can do with this object. Why? Because when you give an interface, you can change the implementation later, and don't worry that other part of code, that is using object through interface, will need changes.
I suppose that you think about things that should plug some behaviour to current class. These things can be called Traits in other programming languages, in another you have multiple inheritance. If you want some implemented logic that is propagated to your classes, you should use abstract classes in java with proper hierarchic. Remember that you can expand classes with inheritance or composition (open-closed principle).
Default methods in Interfaces (Java 8) can be tricky, because they cannot change state of the object. They might be some stubs or mathematics equation that only work with local and static context.

Why we need default methods in Java? [duplicate]

This question already has answers here:
Purpose of Default or Defender methods in Java 8
(5 answers)
Closed 8 years ago.
I'm taking a look to Java 8 news compared to 7 and in addition to very interesting things like lambdas or the new time framework, i found that a new feature(?) was introduced: default methods.
I found the following example in this article:
public interface Math {
int add(int a, int b);
default int multiply(int a, int b) {
return a * b;
}
}
It seems very strange to me.
Above code looks like an abstract class with an implemented method. So, why to introduce default methods in an interface? What is the actual advantage of this approach?
In the same article I read this explaination:
Why would one want to add methods into Interfaces? We’ll it is because interfaces are too tightly coupled with their implementation classes. i.e. it is not possible to add a method in interface without breaking the implementor class. Once you add a method in interface, all its implemented classes must declare method body of this new method.
Well this doesn't convince me at all. IMHO I believe that when a class implements an interface obviosly must declare methods body for each method in it. This is surely a constraint, but it's also a confirm of its "nature" (if you understand what I mean...)
If you have common logic to every inheriting class you'll put it into an implementing abstract class.
So, what's the real advantage of a default method? (It looks more like a workaround than a new feature...)
UPDATE I understand that this approach is for backwards compatibility, but it still doesn't convince me so much. An interface represent a behaviour that a class MUST have. So a class implementing a certain interface has surely this behaviour. But if someone can arbitrarily change the interface, this constraint is broken. The behaviour can change anytime... Am I wrong?
This is for backwards compatibility.
If you have an interface that other people have implemented then if you add a new method to the interface all existing implementations are broken.
By adding a new method with a default implementation you remaining source-compatible with existing implementations.
For a slightly simple/contrived example that should hopefully demonstrate this let us say you created a library:
void drawSomething(Thing thing) {
}
interface Thing {
Color getColor();
Image getBackgroundImage();
}
Now you come to do a new version of your library and you want to add the concept of border colors, that's easy to add to the interface:
interface Thing {
Color getColor();
Color getBorderColor();
Image getBackgroundImage();
}
But the problem is that every single person using your library has to go back through every single Skin implementation they ever did and add this new method.
If instead you provided a default implementation to getBorderColor that just called getColor then everything "just works".
There have been a lot of methods acting on an abstract interface in the past. Before Java 8 they had to be put into an additional class pairing the interface, e.g. Collections with Collection.
This old approach was neither more convincing than default methods nor more practical. Instead of list.sort() you had to say Collections.sort(list). This also implies that you had to make a fundamental decision when creating an interface, either you require every List implementation to implement a sort method or you provide a sort method in a utility class that cannot be overridden.
With default methods you can have both, a standard implementation which the List implementations do not need to implement on its own but still can be overridden if a concrete implementation has a more efficient way to do it knowing its internals, e.g. ArrayList.sort passes its internal array directly to Arrays.sort skipping some intermediate operations.
Suppose at some point you want to add new functionality in declared interface, up to Java 7, If you will add a new method in declared an interface, you also have to define the implementation of the method in classes that are implementing that interface.
In java 8, You can add a default method containing the implementation and all the child class will inherit that method.
Edit : (After question update)
An interface represent a behaviour that a class MUST have
It still represent a behaviour that class must have, your confusion is how you are defining behaviour. All implementing class will inherit default method and are also free to write their own implementation. consider following two cases,
If implementing class does not provide own implementation and simply inherit default method. If you change behaviour of default method in interface, implementing classes will be having updated behaviour as they inherit default method so it holds An interface represent a behaviour that a class MUST have.
If implementing class provide own version of default method, and if you will change behaviour (only arguments) of default method. In this case implementing class will be having two overloaded methods, one which was earlier defined and second one is inherited default method. and if you change complete behaviour (arguments with return type also), It will create ambiguity in implementing class as you can not overload method by changing return type and Implementation will be broken. again it holds An interface represent a behaviour that a class MUST have.
Example :
Bulk data operation in collection is added in Java 8 (Reference : http://openjdk.java.net/jeps/107), to implement that forEach() method is added in Iterable interface. Adding abstract method in Iterable interface would break all the existing code because each class has to implement that method.
Solving the issue, following default forEach() method is added in Iterable interface,
interface Iterable
{
default void forEach(Consumer<? super T> action)
{
for (T t : this) action.accept(t);
}
}
Reference : Java 8 : Default method in Interface

Extending an object vs Implementing an interface

Trying to understand a question I got wrong on a test:
How does inheritance differ from implementing interfaces?
With inheritance, a class gains behavior from its superclass.
With interfaces, a class gains behavior from the interface it implements. (this is the one I chose)
With inheritance, a class must implement the methods defined by its superclass.
With interfaces, a class gains both instance variables and behaviors from the interface it implements.
The way I was thinking is that interfaces define behavior, while superclasses define characteristics... or are they the same? Or am I completely backwards in my understanding?
Edit: I guess I should specify that I do know the difference between interfaces and inheritance. I'm just wondering about the two options which use the term behavior. I don't know if the prof was nitpicking about terminology, or if he asked the question poorly.
I know that when you implement an interface, you have to implement all the methods as defined in the interface. As such, I would say that the interface defines the behavior that a class must have, but extending another superclass (although it does also define some behaviors (more can be given to the subclass), it doesn't seem to fit as strongly as the interface defining behaviors. If the class implements an interface, you can be sure that it has certain behaviors.
Maybe the question was meant to ask whether or not the interface itself has the code for the behavior, or if it's just the definition - which if worded that way, I would have known the answer.
I think some of your misunderstanding might stem purely from semantics. Perhaps a more straightforward way of describing an interface is that it defines an API but does not provide an implementation of that API. One caveat is that I will use Java for my example but in a language like C++, implementing an interface is inheritance of a special sort - namely inheriting from a class consisting of pure virtual functions.
In Java, for instance, you might have an EventListener interface defined as:
public interface IEventListener {
public void handleEvent(Event event);
}
The interface does not, to use the question's verbiage, say anything about how a class that implements the IEventListener interface will behave when it receives an event it only ensures that any class implementing this interface will have the characteristic of being able to receive an event of type Event.
Inheritance, on the other hand, allows super classes to also inherit behavior (implementation). For instance, consider the following Java base class:
public abstract BaseClass {
public void baseMethod(int value) {
System.out.println(int);
}
public class SubClass extends BaseClass {
}
Any class that inherits from BaseClass gains both the API (characteristics) of BaseClass and also the implementation (behavior). In other words not only can you invoke instanceOfSubClass.baseMethod(1), a characteristic, doing so will result in the behavior defined in the BaseClass, namely 1 being printed to the console.
So your answer (2) is incorrect because interfaces do not specify behavior (implementation) only API (characteristics). Inheritance can handle both.
I think the point of the question is to explain that inheritance is specifically useful when you want to share behavior and not just API. That said, implementation (behavior) can also be shared via composition and such a strategy is often better - see Item 16 in Bloch's Effective Java for an excellent discussion.
When you implement an Interface, you don't necessarily care much for the implementation. Also remember that you can implement as many interfaces as you want, since they only specify contracts but not how to fulfill them. The creator of the interface lets you take care of that.
When you extend an Object it's usually because you need some functionality which an already existing object already got the majority of, but will only need that bit extra. Or you want to redefine some of the existing behaviour of an already existing object.
To give you the answer: 1 is right. You don't HAVE to implement the methods of a superclass (Inheritance). Only when it's abstract the next subclass of this superclass needs to implement the methods (like in an interface).
An object implementing an x Interface tells the object that it must do all actions (methods) listed in the definition of an interface. So in the object that implements x, you need to implements all actions. An interface cannot be instanciated.
But when you inherit from an object y, the object y may already have an implementation of some actions. if not the method will be marked as abstract (in java) and you need to implement it in your inherited object.
This is a very common OO design question in Java.
Sincerely recommend this very good article on this topic that explains it well:
http://www.javaworld.com/javaqa/2001-04/03-qa-0420-abstract.html
The correct answer is 1. The answer you chose (option 2) is wrong because interfaces technically do not have any behavior. They are just a list of abstract methods. You can consider them more as a template on which you can base your classes. For example, suppose a project is split into two parts, which need to be integrated at the end. Each team could use a common interface to base their classes on, so that integration would be a much easier job.
with inheritance, you get a cat. with an interface, you get the skeleton of a cat.
You gain behavior and implementation from inheritance. Remember that a subclass inherits all non-constructor and private methods from it's superclass. This means that you may inherit functionality (implementation) of certain methods.
With implementation you gain just behavior. All you are doing with implementation is signing a contract with the compiler, saying that you promise to override all abstract methods defined in the implemented class or interface.
I hope this helped.

Java Object superclass

I have a weird Java question:
As we know:
All Java classes extend java.lang.Object
All Java classes cannot extend itself
Then, java.lang.Object must extend java.lang.Object, which is itself, therefore, it should be impossible. How is Object implemented in Java?
Object is an exception to the first rule, and has no superclass. From JLS3 8.1.4:
The extends clause must not appear in the definition of the class Object, because it is the primordial class and has no direct superclass.
You can also try it out with reflection:
Object.class.getSuperclass(); // returns null
You'd be better off thinking of this as:
All java classes must implement the interface implied by the methods in java.lang.Object.
The concrete class java.lang.Object provides default implementations of these functions.
All other java classes are derived from the object java.lang.Object and may choose to use or override the default implementations of the methods.
The two main points are: all the classes must implement the implied interface and the Java language spec gives you (forces upon you?) default implementations for these methods for free.
Object does not extend itself. It is the superclass for all other objects in the Java language. Think of it as being the level-0 (or root) class of all the objects in the Java API tree - including any objects you create as well.
I also just want to point out that your question is proven impossible by rule #2 that you posted. Your logic used to justify your question only takes #1 into account and is therefore extremely flawed.

When to use abstract class or interface? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Why are abstract or interface classes created, or when should we use abstract or interface classes?
Interface is used when you only want to declare which methods and members a class MUST have. Anyone implementing the interface will have to declare and implement the methods listed by the interface.
If you also want to have a default implementation, use abstract class. Any class extending the abstract class will have to implement only its abstract methods and members, and will have some default implementation of the other methods of the abstract class, which you may override or not.
--EDIT - forgot to mention, Earwicker reminded me
Finally, you can implement as many interfaces as you want, but only extend one class (being it abstract or not). Keep that in mind before choosing.
The key difference is that you can implement multiple interfaces in a class, but only extend a single abstract class. This is because an abstract class can also define fields that store data, whereas an interface cannot.
An abstract class is a class, that has atleast one abstract method or you can also make all your methods as abstract. Obviously it cannot be instantiated. You have to inherit from an abstract class and implement the abstract methods in the inheriting class (i.e, the class extending the abstract class).
Interfaces are not classes at all (so don't call them interface class). Interfaces define the signature of methods without any implementation. Also interfaces have no member-fields. If you implement an interface in a class, you have to provide implementations for all the methods provided by the interface.
It makes sense to define a generalized API for some stuff, that can have completely different implementations. Abstract classes are more useful for classes that do mainly the same, but have some subtle differences. You can combine both approaches.
A good example is the collections framework of the Java class-library. You have the interface List, that defines how Lists have to behave. Some implementations are for instance ArrayList and LinkedList. As they behave similar, the stuff that works the same for both is implemented in the abstract class AbstactList, both inherit this.
See Interface is basically a "Contract". When you are defining an interface you are defining a Contract. Where abstract classes are extended, interfaces are Implemented.
Let's consider an example.
public interface Friend {
void hello();
}
Now you have defined a contract which says that any class which wants to implement Friend needs to provide a definition for method hello().
Here is an implementation:
public class myFriend implements Friend {
public void hello()
println("Done");
}
Now myFriend has fulfilled the contract. Now the question is: Where should interfaces be used?
Interfaces help you define a behavior which must be implemented. Say you have a class A which defines some functionality. You want the other classes to use this class functionality only if they define particular behavior (methods). You enforce this restriction in term of interface.
SamuelCarrijo seems to have answered this question well.
In addition for Java, some frameworks require an interface to work with. I'm thinking of (say) dynamic proxies, or some client/server proxying frameworks. This is because they use introspection on the object to determine methods implemented by the interfaces implemented by the object. So occasionally you have to implement an interface for an object where, perhaps, you wouldn't normally bother.
Note this reason for interfaces is specific to Java.
Abstract classes are used when you are building an inheritance hierarchy. However, most inheritance hierarchies should not be too "deep" (i.e. too many levels of inheritance). Many object oriented design books will favor interfaces over inheritance (one book I read once quoted a developer as saying that "inheritance is the single coolest [object oriented] feature you won't implement"), as this allows classes to be assigned behaviors "by contract", where the contract is the interface.
It is worth noting samuelcarrijo's answer - if you want to have a default implementation of a method, you would have to use an abstract class that has a concrete implementation of the method to give it a default implementation. This default implementation can be overridden in child classes.
Hope this helps!

Categories

Resources