Implementing interface with just one class or more classes - java

Maybe its answer is obvious for most of you but I am a bit confused when implementing an interface.
Should “just one implementation class” implement “the complete set of methods”?
Forex:
public class CCSImplementation implements CCS {
public void addComment (int submissionId,int customerId, String comment, Date date) { }
public void addGeneralComplaint (int submissionId, int customerId, String description, Date date) { }
and other methods…..}
Or
- More implementation classes such as
public class Comment implements CCS {
public void addComment() {}
}
and
public class GeneralComplaints implements CCS {
public void addGeneralComplaint(){}
}
implement the interface part by part taking into account of related methods? (---I got error when implement like these)
Since a reference says
One or more classes can implement that interface...
as I said I am a bit confused.

If the class is abstract, you don't have to implement all/any of the methods:
public abstract class Comment implements CCS {
public void addComment() {}
// addGeneralComplaint() is implied as abstract
}
Depending on your need, it would be perfectly valid to define such a class, where some of the methods are implemented, but subclasses are left to implement the rest of the interface's methods.

When a non-abstract class implements an interface it must provide implementations of all the exposed by the interface methods.
If we have an abstract class A, it can implement an interface without providing method implementations of the interface-exposed methods, since all of them are abstract by default. But when this class is subclassed by a non-abstract class B, the subclass must provide the implementations of the interface-exposed method signatures.

class Comment should extends Class GeneralComplaints
or
class GeneralComplaints should extends class Comment..

If it turns out that you are using an abstract class then you don't have to use everything. From my understanding you only want to implement something if you plan on using the provided methods. It was explained to me that an interface s provided so that the user doesn't forget to use methods in their class. Hope this helps.

Related

Interface and Abstract class share same method

Is this design really valid?
Legacy application code, so just trying to refactor if it's not necessary.
public interface Interface {
public void abc();
}
public abstract class abClass implements Interface{
#Override
public void abc(){
throw new UnsupportedOpException(NOT_IMPLEMENTED_MSG);
}
public class xyz extends abClass{
#Override
public void abc(){
.......//some code here
}
Can I get rid of the Interface? Not sure what's the original intention was behind this design. When would you want to have same methods in both interface and abstract classes which gets eventually overriden?
void abc(); must be implemented either by the abstract class or by the inherited classes...
there is no chance to get rid off that...
if you prefer, you can move the void abc(); as a method of the Abstract class...
redefined it and:
Block the overriding of ot by making it final.
or
delegate the responsability of the implementation to child classes by making it abstract too..
I think, from a functional programming perspective, it's fine as is. Having implements Interface just means the class must have a method with the same name. The fact that it is defined in abClass means that not only are you saying that all classes that inherit from abClass must have the interface, but also that you don't need to redefine it in every class, unless you wish to override.
So you don't actually define the method in Interface, but you do in abClass, and when you define the method in xyz, you're overriding the method in abClass.
An Interface should be used behind an abstract class when it offers something you need and that an abstract class cannot offer.
Create an interface for no concrete reasons but because you think that interface==OOP brings overhead and proves that you misunderstand what OOP is.
In your case, if in the applicative code, you notice that you can remove the interface behind the abstract class and that you have no real impact at compile time, you may wonder if the abstraction of the interface is not just an overhead. It may be useful as not useful. I will develop it.
Using an interface behind a abstract class opens implementation possibilities : you may benefit of this abstract class related with the interface but you can also implement the interface in concrete classes without benefiting of the abstract class, therefore as you wish. Writing an implementation from A to Z may be suitable as not suitable according to our needs.
Personally, I think that the interface is useful behind an abstract class in two cases :
the interface is common for at all types of target concrete classes but the
abstract class is relevant not for all types of target concrete classes.
For example when you implement a decorator, you have a common interface to represent both decorated classes and decorator classes.
The decorator classes have different logic and data from the decorated classes. So, our abstract class for decorator classes or for decorated classes may be different.
Here an simple example to represent Decorator for document.
Common interface :
public interface IDocumentInput {
void read();
byte[] getBytes();
String getStringContent();
}
decorated document :
public class DocumentInput implements IDocumentInput {
private byte[] bytes;
public DocumentInput(byte[] bytes) {
this.bytes = bytes;
}
public byte[] getBytes() {
return bytes;
}
public void read() {
}
public String getStringContent() {
return new String(getBytes(),StandardCharsets.UTF_8);
}
}
abstract class for decorators :
public abstract class AbstractDocumentInputDecorator implements IDocumentInput {
protected IDocumentInput document;
protected byte[] bytes;
public AbstractDocumentInputDecorator(IDocumentInput document) {
this.document = document;
}
public byte[] getBytes() {
return bytes;
}
public final String getStringContent() {
return new String(getBytes(),StandardCharsets.UTF_8);
}
}
Concrete decorator :
public class SecuredDocumentInputDecorator extends AbstractDocumentInputDecorator {
public SecuredDocumentInputDecorator(IDocumentInput document) {
super(document);
}
#Override
public void read() {
document.read();
processUnsecuring();
}
private void processUnsecuring() {
byte[] originalBytes = document.getBytes();
bytes = Base64.decodeBase64(originalBytes);
}
}
In this case, it seems logical to introduce an interface because the abstract class is not enough to represent common behavior and or data of all concrete classes.
You want to provide to developers the possibility to create their own implementation of the interface with or without relying on the abstract class implementation. In general, it's desirable when you create an open API.
Collections in JDK classes illustrate very well that.
Indeed, if you want to create interface/contract promoting extensibility, when you provide only an abstract class, developers which want to create their implementation are forced to use the abstract class even if they don't want. Which is not desirable.
You use a library which forces you to use interfaces. For example with EJB 3.0 and Spring in these first versions, using abstract class or class doesn't allow to benefit from some of their features.

Serializable interface in Java

I understand that the whole point of having an interface is to force the class that implements it to implement/define all the abstract methods in that interface.
However, in the process of Object Serialization in Java (conversion into byte stream), the class the object to be serialized is an instance of must implement the Serializable interface. However, I see no methods of the interface being defined. So, is that an interface with ZERO methods, if yes, is that even possible and if yes again, what is the purpose if it has no methods?
The Serializable interface is a marker interface. If a class implements it, the runtime system knows that the class is serializable.
In modern Java this effect could now be achieved with an annotation but they were not around at the time this interface was defined.
Yes such an interface is possible. It is called a marker interface. There are other interfaces like this also.
You can have a look at
http://mrbool.com/what-is-marker-interface-in-java/28557
As I already stated, purpose of interface with 0 methods is about pure contract.
Let me explain it in next example:
Let's say we have a simple data access layer composed of multiple interfaces like:
DeletableDao, InsertableDao, UpdatableDao etc.. and implementation class like DaoImpl:
Let's say we have entity class like this:
public Person implements DaoEntity {
private int id;
private String name;
// getters and setters
}
where DaoEntity is interface with 0 methods because of pure contract:
public DaoEntity {
}
and let's say that our DeletableDao looks like this:
public interface DeletableDao<T extends DaoEntity> {
void delete(T t);
}
and implementation class:
public DaoImpl implements DeletableDao<Person> {
public void delete(Person p) {
// Delete person
}
}
What this all means? What is a purpose of DaoEntity interface? It means that only instance of DaoEntity subclass can be passed to delete method and deleted.

Should I implement all the methods present in an abstract class?

Below is the code snippet:
public abstract class MyAbstractClass {
public abstract void a();
public abstract void b();
}
public class Foo extends MyAbstractClass {
public void a() {
System.out.println("hello");
}
public void b(){
System.out.println("bye");
}
}
public class Bar extends MyAbstractClass {
public void a() {
System.out.println("hello");
}
public void delta() {
System.out.println("gamma");
}
}
There are couple of questions that I have:
Q-1 :- Should I implement ALL the methods in abstract class?
Q-2 :- Can the implementing class have its own methods?
When you extend an Interface or an Abstract class you are creating a contract of sorts with that superclass. In the contract you are saying:
"I will implement all unimplemented methods in my superclass"
If you do not, implement all the unimplemented methods, then you are breaking your contract. A way to not break your contract is make your subclass Abstract as well as a way of saying
"I have not implemented all the classes in my contract, I am going to
have my subclasses implement them".
For your class bar right now, you must implement b() or make bar an Abstract class or you are not fulfilling your contract with MyAbstractClass
The basic idea is:
Interface: None of my methods are implemented. A subclass must implement all my methods in order to implement me. (Note: I believe default interfaces have been added to Java 8 which may change this a bit)
Example:
public interface myInterface
{
//My subclasses must implement this to fulfill their contract with me
public void methodA();
//My subclasses must implement this to fulfill their contract with me
public void methodB();
}
Abstract: I may implement some of my methods, but I will also leave methods as abstract so that my subclasses must implement because they can implement those classes to suit their needs better than I can.
Example:
public abstract class myAbstractClass
{
//My subclasses must implement this to fulfill their contract with me
public abstract void methodC();
public void helloWorld()
{
System.out.println("Hello World");
}
}
Abstract classes can also extend interfaces so they can implement some of their methods. But they can also leave some of the methods unimplemented so the subclass can implement them. If you leave an interface method unimplemented, there is not need to declare it abstract, it is already in the contract.
Example:
public abstract class myAbstractClass2 implement myInterface
{
#Override
public void methodA()
{
// this fulfills part of the contract with myInterface.
// my subclasses will not need to implement this unless they want to override
// my implementation.
}
//My subclasses must implement this to fulfill their contract with me
public abstract void methodD();
}
So in essence, an abstract class doesn't have as strict a contract with it's superclass because it can delegate its methods to its subclasses.
Regular Class: (I use regular to mean non-interface, and non-abstract). I must implement all unimplemented methods from all of my superclasses. These classes have a binding contract.
Example:
public class mySubClass extends myAbstractClass2
{
#Override
public void methodB()
{
//must be implemented to fulfill contract with myInterface
}
#Override
public void methodD()
{
//must be implemented to fulfill contract with myAbstractClass2
}
public void myMethod()
{
//This is a method specifically for mySubClass.
}
}
Q-1:- Should I implement all methods in abstract class?
Yes, you must implement all abstract methods.
Q-2 :- Can the implementing class have its own methods?
Yes, you can declare own (more specfic) methods.
You not only should, but have to implement all abstract methods (if the subclass is non-abstract). Otherwise an object of that subclass wouldn't know what to do if that method was called!
The only way to prevent this is if the subclass is also declared abstract, so that it cannot be instantiated in the first place.
You don't have to implement all methods of an abstract class. But you must implement all abstract methods of it.
In fact extending an abstract class has no difference then extending a normal class. It's not like implementing interfaces. Since you're extending you are creating a subclass thus you can add as many methods and attributes as you need.
Ya definately implementing class can define its own method as well and if are not implementing all the methods of your abstract class in the derived class then mark this derived class also as Abstract
but at the end of chain you have to make one concrete class which implements all the method that was not implement in abstract sub-parent
public interface I{
public void m();
}
public abstract class A1 implements I{
//No need to implement m() here - since this is abstract
}
public class B1 extends A1{
public void m(){
//This is required, since A1 did not implement m().
}
}
public abstract class A11 extends A1{
//Again No need to implement m() here - since this is abstract
public abstract void newA11Method()
}
public class B11 extends A11{
//This class needs to implement m() and newA11Method()
}
Yes, the implementing class need only implement the methods labeled as abstract in the abstract class.
Yes you must implement all the methods present in an abstract class. As the purpose of abstract class is purely to create a template for the functions whose implementation is decided by the class implementing them. So if you don't implement them, then you are breaking the concept of abstract class.
To answer your second question, yes you can create any number of your own methods irrespective of the abstract class you are extending.
Yes, When you are implementing an Interface you will have to implement all its methods. That is the purpose of defining an Interface. And yes, you can have your own methods in the class where you implement an Interface.
Yes, when you extends abstract you should give implementation for all abstract methods which are presents in abstract class. Othrewise you should make it implementation class as abtract class.
You must implement all the abstract methods you have in the abstract class. But you can directly use the concrete methods that are implemented.
For more information please refer to the :
https://www.javatpoint.com/abstract-class-in-java

Abstract class with all methods abstract - Practical Example

I am asking a very basic question and it may be marked duplicate (I could not find the answer though):
Is there any practical example of an Abstract Class with all the
methods declared as Abstract?
In most cases and as mentioned in Java Tutorial also, class with all methods abstract shall be an interface.
But since abstract class and interface are two different concepts, I am looking for an example compelling to have "complete abstract class"
The only practical approach i think is that Abstract class can hold state. So you can have inside properties with access level protected, and you can make protected abstract methods that in interface you can't cause all are public.
A practical example could be for example this, the protected method in java has 'inheritance access' and 'package access'.
public interface Operation{
void operate();
}
public abstract class AbstractClase implements Operation{
protected Operation delegate;
public AbstractClase(Operation delegate){
this.delegate=delegate;
}
//delegate implementation responsability to children
protected abstract doSomething();
}
The downside of using abstract class is that you loss the possibility to extends of something else too.
As well as for holding state, it's worth remembering that all interface members are implicitly public. So restricting visibility of abstract methods may itself be a compelling enough reason to use an abstract class instead of an interface.
Adding to the two answers given above, Interfaces can only have constants(Variables which are public,static and final) while there is no such restrictions for abstract classes.
Abstract classes can have constructors which will be implicitly called when a child class is instantiated (if it is non-parameterised). But this is not possible with interfaces.
Here is an example for the usage of an abstract class
abstract class Animal{
public int noOfLegs;
public boolean isAlive;
Animal(){
isAlive = true;
}
public abstract void walk();
}
class Cow extends Animal{
Cow(){
noOfLegs = 4;
}
public void walk(){
if(isAlive){
//Code for walking
}
}
}
One other general purpose of an abstract class is to prevent an instance of the class., for example
abstract class Mammal{
int i=0;
}
public class Man extends Mammal{
public setMeValue(int i){
this.i=i;
}
public static void main(String args[]){
Mammal m= new Man();
man.setMeValue(10);
}
}
In the above code, I effectively make sure that there will never be an object of instance Mammal.
An interface can be applied to wildly different classes. Classes that have no relation to each other are Serializable or Cloneable. However, subclasses of an abstract class are all related. This may not mean anything when implementing the interface or extending the abstract class, but it means something semantically.
There is a style of programming where all the methods of a base class are either public final, protected abstract, protected and empty, or private. But even that isn't what the OP was interested in.
Adding more to the below answers:
Interface provide you with a contract to implement where abstract Class may provide you with a template as well. For a simple scenario you can use an Interface or an abstract Class without thinking much. But having an abstract class just for maintaining a state might give you lot of problems in a complex implementation. In such cases you have to carefully consider what you really want to achieve in your code and make the decision. If you consider the case of maintaining the state in your code, you can always use the State pattern in your implementation, so you will be able to use an interface in your code. You should always consider the extend-ability and maintainability of your code before deciding to use an abstract class over interface.
The simplest practical example I can think of is a class that has a protected variable:
public abstract class RoadVehicle {
protected int numberOfTires;
protected String vinNumber;
protected VehicleRegistration registration;
public abstract void drive();
public abstract double calculateToll();
public abstract void changeTires();
// so on and so forth...
}
You can't do this with an interface.
public abstract class animal{
public abstract void speak(){
System.out.println("animal voice");
}
}
public class dog extends animal{
public void speak(){
System.out.println("dog voice");
}
}
The biggest motive behind having Pure Abstract classes is to allow future extension. Assume you have an Abstract class (with all abstract members), then you inherit that abstract class in 20 derived classes. Sometime in future you wish to add a public method to 5 of your derived classes, what do you do ?
Since you already inherit the abstract class, an easier solution is to add the method (with implementation) to the abstract class. This way you don't have to touch any of the derived classes. Interfaces are very rigid in this context, once created there is very little chance to change an Interface, as it would require changing all the classes that implement that Interface.

Is there a way to guarantee an interface extends a class in Java?

Suppose I have the following situation:
public abstract class Vehicle {
public void turnOn() { ... }
}
public interface Flier {
public void fly();
}
Is there a way that I can guarantee that any class that implements Flier must also extend Vehicle? I don't want to make Flier an abstract class because I want to be able to mix a few other interfaces in a similar manner.
For instance:
// I also want to guarantee any class that implements Car must also implement Vehicle
public interface Car {
public void honk();
}
// I want the compiler to either give me an error saying
// MySpecialMachine must extend Vehicle, or implicitly make
// it a subclass of Vehicle. Either way, I want it to be
// impossible to implement Car or Flier without also being
// a subclass of Vehicle.
public class MySpecialMachine implements Car, Flier {
public void honk() { ... }
public void fly() { ... }
}
Java interfaces cannot extend classes, which makes sense since classes contain implementation details that cannot be specified within an interface..
The proper way to deal with this problem is to separate interface from implementation completely by turning Vehicle into an interface as well. The Car e.t.c. can extend the Vehicle interface to force the programmer to implement the corresponding methods. If you want to share code among all Vehicle instances, then you can use a (possibly abstract) class as a parent for any classes that need to implement that interface.
You could rearrange your classes and interfaces like this:
public interface IVehicle {
public void turnOn();
}
public abstract class Vehicle implements IVehicle {
public void turnOn() { ... }
}
public interface Flier extends IVehicle {
public void fly();
}
This way all implementations of Flier are guaranteed to implement the protocol of a vehicle, namely IVehicle.
If you have control on the Vehicle classes just extract Vehicle as an interface and then provide a base implementation.
If you have no control over Vehicle class, for example because it is part of a framework you are using or a third party library, it's not possible to do in Java.
The closest thing you can do is using Generics multiple wildcards notation.
<T extends Vehicle & Car>
But you can't really apply it directly to Car unless you do something like this:
public interface Car<T extends Vehicle & Car>() {
T self();
}
Which is bot weird and do not enforce the self method to actually return self, it's just a strong hint/suggestion.
You would implement a Car like this:
public class CitroenC3 extends Vehicle implements Car<CitroenC3> {
#Override
public CitroenC3 self() {
return this;
}
}
one can use a Car<?> like this:
Car<?> car = obtainCarInSomeWay();
Vehicle v = car.self();
Car c = car.self();
they should be both valid syntax.
What the compiler enforce here is that what you specify in Car<WHICH> as WHICH must both extend Vehicle and implement Car. And by adding self() you are saying to the programmer that the T object is supposed to be the object itself, thus forcing the wildcard instance to match the class if he want to be compliant with the specification.
in Java 8 you can even define a default implementation for the self method.
I also wish there was a better way to handle something like this.
It's a strange requirement, but you can accomplish something of the sort with Generics:
<T extends MyInterface & MyAbstractClass>
This question shows that you haven't grasped the essence of interface and class. Forgetting the concrete Java syntax right now, all you need to understand first is that: interface is a set of protocol, which should be implementation-agnostic. It makes no sense to let an interface extend a class(which is implementation-oriented).
Back to your concrete question, if you want to guarantee that a Flier is always a kind of Vehicle, just change the latter to an interface and let former extends it(It does make sense to extend one protocol from the other protocol). After that, you may create any class(abstract or concrete) that implements Vehicle or Flier.
Define a new Package
Create a new interface (ie. HiddenOne) with scope "default" with a method "implementMe(HiddenOne)"
Move Vehicle and Flier to the new Package.
Inherit Vehicle and Flier from HiddenOne
Implement the method implementMe in Vehicle.
Now: Whenever you like to implement from "Flier" you must extends from Vehicle !
(because only Vehicle can implement implementMe).
This is tricky but works great.

Categories