How to handle the need of two abstract classes, in Java? [duplicate] - java

This question already has answers here:
Java Multiple Inheritance
(17 answers)
Closed 2 years ago.
Java does not allow multiple superclasses; and interfaces cannot have method bodies as I know. So how to handle the case in which I want to inherit two implemented methods of different superclasses.
Suppose that I create classes for objects which can do some specific tasks, let's say objects can play and sing. Some objects only play and their subclasses as well, so there is no need to define the exact same play() method for each subclass, I define it in superclass Player. Some objects only sing, so, I define the generic sing() method in superclass Singer, not in each subclass. What to do, if a subclass can sing and play, so need to extend Player and Singer superclasses to be able to apply implemented play() and sing() methods of superclasses. How to handle that kind of situation, in the best efficient way?

Starting with Java 8 interfaces can have default methods. These methods are marked with the default keyword and can have an implementation in the interface, that can then be used in (or reimplemented by) classes implementing the interface. Classes can also implement multiple interfaces, so you could have a class implement both Player and Singer and provide default methods play() and sing() in their respective interfaces. This is also useful if you want to modify an interface without having to also modify the classes that already implement it.

Related

Why interfaces have some methods of Object class? [duplicate]

This question already has answers here:
Do interfaces inherit from Object class in java
(9 answers)
Closed 2 years ago.
I came across fact that Collection interface has methods equals and hashCode which are also contained in Object. Same is the case with List interface. I was having following doubts:
Why interfaces should have these methods? Is it only because they have different meaning than those in Object ?
According to this question, including these methods does not enforce the implementing class to provide their implementation as these implementations are already provided and inherited from Object. So technically including them in the interfaces does not have any effect. This again underlines importance of first doubt, why interfaces need to have these methods?
This page says:
These methods perform computations over the object’s state, but the interface, in general, has no access to state; only the implementing class has access to this state.
Which I feel further increases importance of first question.
If we at all need them in interfaces, then why Java framework dont have super-interface containing them and have such interfaces implement this interface, just like as all classes are subclasses of Object?
The List interface declares equals and hashCode so that it can document extra constraints that the implementations must follow. For example, the List interface documentation requires that the equals method must consider two lists equal if the have the same items in the same order, no matter how the lists are implemented.
There is no way the compiler or runtime can enforce these requirements, so breaking them leads to runtime bugs that may be hard to find.

Java 8 Need of Defender (default) Methods [duplicate]

This question already has answers here:
When to use: Java 8+ interface default method, vs. abstract method
(16 answers)
Closed 7 years ago.
Why We need Defender methods in interfaces in java 8 as we already have abstract classes.I found various answers on internet like:
To add external functionality
But Abstract class is for partial Abstraction where as our interface is actually a pure abstract class so why their is a default method inside an interface?
The problem with sharing functionality by placing it in an abstract base class is that a class can derive from exactly one base class. This is a limitation in cases when you would like to inherit functionality from more than one base.
Sharing functionality through an abstract base class may also become a problem when you need to implement an interface from a class that already has a base class. In this case you cannot derive your new class at all, because you must pick one of the two bases, when presumably you want both.
Default methods solve this problem with elegance: placing your common implementation into the default method allows you to share the code without limitations.
You can think of the main difference between default methods and inheriting an abstract class as the difference between sharing functionality horizontally across siblings that implement the same interface, or vertically among children that inherit from the same base class.
Here is an examoke: consider an interface that looks like ResultSet of JDBC, which has two ways of accessing the same column - by name and by index. The interface could be coded up like this:
interface ResultSet2 {
int findColumn(String columnLabel);
String getString(int index);
long getLong(int index);
default long getLong(String columnLabel) {
return getLong(findColumn(columnLabel));
}
default String getString(String columnLabel) {
return getString(findColumn(columnLabel));
}
}
Anyone implementing ResultSet2 would have to implement three methods, and get the remaining two for free. They would have an option to provide an alternative implementation, but that would be optional.
The main reason behind defender methods is to be able to extend long-existing interfaces with new functionality, without breaking the existing code. Particulary with Java 8 lamba expressions they introduced a lot of new methods on collection interfaces, like Iterable.forEach. With providing default methods, existing classes implementing the Iterable interface dont have to be altered to use in Java 8 environment.
The original intent was to compete with C#'s extension methods. Given core methods of an interface, e.g. get(), set() in List, extention methods (e.g. sort()) can be defined and implemented.
Java guys argued that it would be better to declare such methods on the interface itself, rather than in external places; so that the methods could be overridden by subtypes, providing optimal implementations per subtype. (They also argued that such methods should be controlled by the interface authors; this is rather a soft point)
While default methods can be added to existing interfaces, it is very risky of breaking existing 3rd party subtypes, particularly for very old types like List with lots of subtypes in the wild. Therefore very few default methods were added to existing core Java APIs. See this question.
For new interfaces, default method is a very valuable tool for API designers. You can add a lot of convenience methods to an interface, for example, Function.compose(). Subtypes only need to implement abstract/core methods, not default methods (but they can if they want to).
I disagree with the idea that default methods can "evolve" interfaces. They do not change the core semantics of an interface, they are just convenience methods (in the form of instance method).
And default methods should be carefully designed up-front when the interface is designed; as said, it is very risky to add default methods afterwards.
C#'s extension method allows 3rd party to add convenience methods; this is very nice, and there is no reason why Java couldn't introduce something similar in future.

When to use interfaces compared to Abstract classes? [duplicate]

This question already has answers here:
When to use an interface instead of an abstract class and vice versa?
(26 answers)
Abstract class vs Interface in Java
(15 answers)
Closed 8 years ago.
I understand the technical difference between the two, but I don't understand why one is better to use than the others? Can anyone give me an example that would help me distinguish an advantage one has over the other?
For example: If I was making an rpg game, and I was working on some healing items. What would the uml diagram look like. Would I be using an interface for items, and then healing items or abstract classes.
When to use interfaces
Interfaces are basically used to inherit the behaviour, as we know interfaces can only have abstract methods. When a class implements that interfaces it has to implement all its abstract methods (unless the class itself is an Abstract class), thus it behaves according to the way interfaces defines.
For example, if you want your class to behave as a Thread. You need to implement Runnable interface and override its run() method.
We need to inherit behaviour of two or more forms.
Interfaces are basically created when we know what to do, but we don't know how to do it. To explain in simpler terms I would say, suppose there are 5 tasks which you know must be done. But there can be different ways to do them. Any class implementing them can do them in any way they wish to. So create an interface and put your methods in them.
When to use Abstract class
We know abstract classes can have both abstract as well as concrete methods.
So same example, if you have 5 tasks to be done but for one task there is one default way to do, so you will wish to define its body and you won't be able to do so in interfaces.
In this case we'll create an abstract class. Put 4 abstract methods and one concrete method, which will be inherited by its child classes directly and they won't need to define it on their own. However if they wish they can override its functionality.
Also keep in mind, a class can extend only one abstract class at a time.

Abstract Class V/s Interface in Design Java [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to use abstract class or interface?
I am a newbie in Java , can anyone please explain a scenario where abstract class will be
useful and interface will not be and vice versa.
I believe in not so complex problems both can solve the issue with equal ease.
Please explain in layman's term and pardon my ignorance!
When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.

Is a Java interface an abstract class? [duplicate]

This question already has answers here:
implicit super-interface in Java?
(4 answers)
Closed 4 years ago.
I'm working through some homework and a question on a previous exam paper asks to name all of the abstract classes in a given UML diagram. Fairly straightforward, I suppose. There are one abstract class and three interfaces. Do these interfaces qualify as abstract classes, in general?
Thing is, while technically interfaces may be represented as classes in languages like Java, I wouldn't consider them classes.
Abstract? Hell yes. Class? No.
Interfaces cannot have constructors, neither properties, fields, function bodies, etc. Interfaces cannot be inherited, they are implemented (again, technically it might be true that implementing an interface is actually inheriting it in specific languages, but that's not my point.) Interfaces are more like 'contracts' as they do not define any behaviour whatsoever like classes.
Now if this is a homework then you shouldn't really argue about these sort of stuff with the teacher. Just check your lecture notes and see if the word "class" is mentioned anywhere in the your teacher's definition of interface.
All interface are indeed abstract
Actually, you can declare an method as abstract within an interface... except any 'checkstyle' tool will tell you the abstract keyword is redundant. And all methods are public.
If a class implements an interface and does not implement all its methods, it must be marked as abstract. If a class is abstract, one of its subclasses is expected to implement its unimplemented methods.
To echo other answers, an interface is not a class.
An interface is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.
Interfaces are not part of the class hierarchy, although they work in combination with classes.
When you define a new interface, you are defining a new reference data type. You can use interface names anywhere you can use any other data type name. If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface
To better explain why an interface is not a class, consider the following:
1/ an interface is a type used by values
2/ a class is for Objects
3/:
Object a = new Date();
String s = a.toString();
The type of the variable 'a' is Object (which is actually a type notation in Java source code meaning a reference to an Object),
but the class of the object it points to is Date.
The type (Object) only affects what code is valid according to the compiler's type-checking, but not what the code actually does.
The class of the object affects what the code does, so that the a.toString() call in the second line returns a String that looks like a Date, not one that looks like "java.lang.Object#XXXXXXXX".
Since an Interface is a type, it is used for values only, and will not represent what objects will actually do in term of runtime.
In Java though, theres a twist to the tale - all Interfaces in Java extend java.lang.Object! Try adding a method:
public void notify();
in an interface and see what happens..
An Interface extending a Class - Does that make the Interface a Class? Or the Class an Interface?? Uhh-huh.. Guess it was a hack that had to be done to prevent interfaces overriding the definitions in java.lang.Object that implementations of the interface had to extend anyway.
You've only asked about the abstract side, but don't forget the class side - I wouldn't call an interface a class, so even though interfaces are abstract (as per the specification), I still don't think they count as abstract classes. It may be worth explicitly explaining that though :)
Yes, an Interface is implicitly Abstract. Look behind the scenes as to the way it is encoded to a .class file.
Semantics are a funny thing though; under exam conditions "abstract class" would have to literally be compiled from a .java source file using abstract class in the Class' declaration.
An interface contains prototype of methods (i.e Declaration ) not defination but Abstract class can contain defination of method & atleast one Abstract method (method with only prototype)
Interfaces are used to break the Object Inheritance.
They could hold two or more objects of several classes
and classes hierarchies.
Look at an interface as an outlet plug. All classes
implementing an Interface need to have one, the same
way a computer, a coffee machine, a ventilator and a
refrigerator need to have the same device to get
power.
Abstract class looks like interface. Abstract classes can have implementations where as interface can't have any implementations.
Then, there is a question. Can we call abstract class as interface if they only have method signatures?
I think, abstract classes, unlike interfaces, are classes. They are expensive to use because there is a lookup to do when you inherit a class from abstract class.

Categories

Resources