Interface and Abstract class share same method - java

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.

Related

abstraction can be done without inheritance? java

Is abstraction possible without inheritance? This is my code
abstract class whatever
{
abstract void disp1();
abstract void disp2();
abstract void disp3();
}
class what {
void disp1()
{
System.out.println("This is disp1");
}
}
public class threeClasses {
public static void main (String args[])
{
what obj =new what();
obj.disp1();
}
}
Please note above, how i:
did not extend the class "what" from abstract class "whatever" and yet the code runs perfectly with no errors
Did not declare class "what" as abstract (since it's not declaring the other two methods disp2() and disp3())
I am very confused. Please help.
You aren't using whatever (and Java naming conventions should be respected). The idea behind an abstract class (and inheritance) is that there is an interface contract. Let's examine it with a more practical example,
abstract class Whatever {
abstract void disp1();
void disp2() {
System.out.println("disp2");
}
void disp3() {
System.out.println("disp3");
}
}
Then make What extend it. Override two methods for demonstration (the annotation is a useful compile time safety check)
class What extends Whatever {
#Override
void disp1() {
System.out.println("This is disp1");
}
#Override
void disp2() {
System.out.println("This is disp2");
}
}
Finally, invoke methods on a What instance through the Whatever contract
public static void main(String args[]) {
Whatever obj = new What();
obj.disp1();
obj.disp2();
obj.disp3();
}
Which outputs
This is disp1
This is disp2
disp3
Note that What is providing the implementation for disp1 and disp2 while Whatever provides disp3.
There is no relationship between your abstract class and your concrete class. Whatever your definition of "abstraction", it actually represents a relationship between types. The abstract keyword does not establish that relationship between classes, it represents that relationship, and not by itself. The relationship needs to be extended from both sides.
abstract is a declaration from one side about a promise that must be kept, for an inheriting type either to implement abstract methods or to ask for that promise from its inheriting types.
The other side makes the promise by being a class that inherits from the abstract type. Without inheritance, the concrete type loses the is-a connection.
You will get the compiler error you're complaining about missing if you correct one major mistake you made. You failed to use the #Override annotation. Always use the #Override annotation when you intend to override a method, or you will forever enjoy just the sort of bug you show here.
I think what he meant was if we can implement abstract class's method without inheriting abstract class.
You might be thinking if we can do it with composition/association/aggregation relation.
To that, I will answer: NO because you can't create an object of abstract class as in these relations you have to make object or reference of the object.
So, the only way to implement abstract methods is through inheritance.

Why its not necessary to have abstract classes to have abstract method [duplicate]

Can have an abstract class implementing all of its methods-- with no abstract methods in it.
Eg.:
public abstract class someClass {
int a;
public someClass (int a) { this.a = a; }
public void m1 () { /* do something */ }
private void m2 () { /* do something else */ }
}
What's the advantage, if any, of having such an abstract class compared to having the same class as a concrete one instead?
One i can think of is that, when i declare it as abstract, it won't be instantiated.
however, i can have the same effect by making it concrete and its constructor(s) private.
TIA.
//==================
EDIT: One other use I can think of:
it may be extending another abstract class or implementing an interface without implementing that class's abstract methods-- although it is implementing all methods of its own. for whatever it' worth.
It has a conceptual meaning: this class has a behaviour which makes no sense on its own.
Granted, it's difficult to imagine such a scenario without well-defined extension points (i.e. abstract methods), but occasionally it will be a reasonably accurate model of your problem.
You can have something like this:
public abstract class ObjectWithId {
private final String id;
public ObjectWithId( String id ) {
this.id = id;
}
public final String getId() {
return id;
}
}
And then you can extend it to declare different types of objects that have ids. Here you have a fully specified and implemented behaviour but no restriction on any other behaviours subclasses may exhibit.
Note though that a much neater way to model the same thing is to use composition instead of inheritance.
public final class ObjectWithId<T> {
private final String id;
private final T ob;
public ObjectWithId( String id, T ob ) {
this.id = id;
this.ob = ob;
}
public String getId() {
return id;
}
public T getObject() {
return ob;
}
}
But before generics were introduced (up to Java version 1.4), this wouldn't have been as elegant and obviously better than the abstract class solution because you'd have had to trade in type safety.
you can declare to implement an interface and don't provide implementation and then each child implicitly gets interface extended
you prevent to create instance of this class
you in future provide common implementation to all children
As you pointed out, you can prevent the class from being instantiated by making it's constructor private. Othere than that, there is no benefit whatsoever. This is probably supported just to provide language completeness.
We generally use Abstraction concept with inheritance
Consider using abstract classes if any of these statements apply to
your situation:
You want to share code among several closely related classes.
To answer your question,
Why declare a class with concrete methods Abstract?
One possible reason is to support inheritance without actually creating objects
Assume you have two classes one Abstract and other Concrete
Abstract class : AbsClass
abstract class AbsClass {
int a = 5;
//Constructor
public AbsClass() {
System.out.println(a);
}
void methodA() {
System.out.println(a + 10);
}
}
and
Concrete class : ConcreteClass
class ConcreteClass {
int a = 10;
//Made the constructor Private to prevent from creating objects of this class
private ConcreteClass() {
System.out.println(a);
}
void methodA() {
System.out.println(a + 10);
}
}
The above two classes should function similarly (?) Until you try to Subclass them
class AbsImplementer extends AbsClass {
//Works fine
}
class ConcImplementer extends ConcreteClass {
//Compilation Error Implicit super constructor ConcreteClass() is not visible
}
The practical difference is that you can't create an instance of it. You would have to subclass it and create an instance of the subclass.
As to WHY you would want to do this, in practice ... I'm hard pressed to think of a good reason. You could say that the class is only meaningful if someone creates a subclass that implements some function. But then why not make that function abstract in the super-class?
I wouldn't rule out the possibility that someone might come up with some example where this makes sense, but I can't think of one. Just because it's possible to write a piece of code and that code compiles successfully doesn't mean that that it makes sense. I mean, I can write "total_price = item_price * zip_code + customer_height_in_cubits - 7.879", but that doesn't mean such a line of code would be meaningful.
Well assume that you don't care whether the methods of the abstract class are implemented or abstract, but by design it has to be abstract so that when someone extends it, they have to add more methods or override the existing ones or use as is. If they don't want to override the methods then the default behavior is already provided in that abstract class.
In this abstract class, the only criteria you enforce is - one simply cannot instantiate that class and they have to have their only version of class before using it.
So in general, abstract class with few or all methods being implemented, is much better than having an interface which has no methods implemented at all. This is based on the assumption that you are using it as a single inheritance.
Consider something similar to the NVI pattern (not sure what you'd call it in Java):
public abstract class A {
public final void doSomething() {
System.out.println("required");
doOptional();
}
protected void doOptional() {
System.out.println("optional");
}
}
public class B extends A {
#Override
protected void doOptional() {
System.out.println("overridden");
}
}
For your public API, you only expose a public final method which cannot be overridden. It performs some required work inside there and an optional method. When extending this class, you can only override doOptional().
Calling B.doSomething() will always print "required" before it proceeds.
Since doOptional() is not abstract, there's no purely code reason that class A needs to be abstract. But it might be desired for your particular project. For example, a base service that is always extended into specific sub-projects.
This can be useful for cases when the classes derived from the abstract base class must have some behaviour that is different from each other but that behaviour can not be abstracted as residing within a method that has the same signature for all the classes. Being unable to share a signature can occur if the different behaviour requires methods that are passed different primitive types. Because they use primitive types you can not use generics to express the similarity.
An abstract base class without any abstract methods is acting a bit like a marker interface, in that it is declaring that implementing classes must provide some behaviour without having that behaviour encapsulated within a new method with a signature that is the same for all implementations. You would use an abstract base class rather than a marker interface when the implementing classes have some behaviour in common, especially if the base class can implement it for the derived classes.
For example:
abstract class Sender {
protected final void beginMessage() {
...
}
protected final void endMessage() {
...
}
protected final void appendToMessage(int x) {
...
}
}
final class LongSender extends Sender {
public void send(int a, int b, int c) {
beginMessage();
appendToMessage(a);
appendToMessage(b);
appendToMessage(c);
endMessage();
}
}
final class ShortSender extends Sender {
public void send(int a) {
beginMessage();
appendToMessage(a);
endMessage();
}
}
It can be useful if you consider it an utility class.

What's the point in having an abstract class with no abstract methods?

Can have an abstract class implementing all of its methods-- with no abstract methods in it.
Eg.:
public abstract class someClass {
int a;
public someClass (int a) { this.a = a; }
public void m1 () { /* do something */ }
private void m2 () { /* do something else */ }
}
What's the advantage, if any, of having such an abstract class compared to having the same class as a concrete one instead?
One i can think of is that, when i declare it as abstract, it won't be instantiated.
however, i can have the same effect by making it concrete and its constructor(s) private.
TIA.
//==================
EDIT: One other use I can think of:
it may be extending another abstract class or implementing an interface without implementing that class's abstract methods-- although it is implementing all methods of its own. for whatever it' worth.
It has a conceptual meaning: this class has a behaviour which makes no sense on its own.
Granted, it's difficult to imagine such a scenario without well-defined extension points (i.e. abstract methods), but occasionally it will be a reasonably accurate model of your problem.
You can have something like this:
public abstract class ObjectWithId {
private final String id;
public ObjectWithId( String id ) {
this.id = id;
}
public final String getId() {
return id;
}
}
And then you can extend it to declare different types of objects that have ids. Here you have a fully specified and implemented behaviour but no restriction on any other behaviours subclasses may exhibit.
Note though that a much neater way to model the same thing is to use composition instead of inheritance.
public final class ObjectWithId<T> {
private final String id;
private final T ob;
public ObjectWithId( String id, T ob ) {
this.id = id;
this.ob = ob;
}
public String getId() {
return id;
}
public T getObject() {
return ob;
}
}
But before generics were introduced (up to Java version 1.4), this wouldn't have been as elegant and obviously better than the abstract class solution because you'd have had to trade in type safety.
you can declare to implement an interface and don't provide implementation and then each child implicitly gets interface extended
you prevent to create instance of this class
you in future provide common implementation to all children
As you pointed out, you can prevent the class from being instantiated by making it's constructor private. Othere than that, there is no benefit whatsoever. This is probably supported just to provide language completeness.
We generally use Abstraction concept with inheritance
Consider using abstract classes if any of these statements apply to
your situation:
You want to share code among several closely related classes.
To answer your question,
Why declare a class with concrete methods Abstract?
One possible reason is to support inheritance without actually creating objects
Assume you have two classes one Abstract and other Concrete
Abstract class : AbsClass
abstract class AbsClass {
int a = 5;
//Constructor
public AbsClass() {
System.out.println(a);
}
void methodA() {
System.out.println(a + 10);
}
}
and
Concrete class : ConcreteClass
class ConcreteClass {
int a = 10;
//Made the constructor Private to prevent from creating objects of this class
private ConcreteClass() {
System.out.println(a);
}
void methodA() {
System.out.println(a + 10);
}
}
The above two classes should function similarly (?) Until you try to Subclass them
class AbsImplementer extends AbsClass {
//Works fine
}
class ConcImplementer extends ConcreteClass {
//Compilation Error Implicit super constructor ConcreteClass() is not visible
}
The practical difference is that you can't create an instance of it. You would have to subclass it and create an instance of the subclass.
As to WHY you would want to do this, in practice ... I'm hard pressed to think of a good reason. You could say that the class is only meaningful if someone creates a subclass that implements some function. But then why not make that function abstract in the super-class?
I wouldn't rule out the possibility that someone might come up with some example where this makes sense, but I can't think of one. Just because it's possible to write a piece of code and that code compiles successfully doesn't mean that that it makes sense. I mean, I can write "total_price = item_price * zip_code + customer_height_in_cubits - 7.879", but that doesn't mean such a line of code would be meaningful.
Well assume that you don't care whether the methods of the abstract class are implemented or abstract, but by design it has to be abstract so that when someone extends it, they have to add more methods or override the existing ones or use as is. If they don't want to override the methods then the default behavior is already provided in that abstract class.
In this abstract class, the only criteria you enforce is - one simply cannot instantiate that class and they have to have their only version of class before using it.
So in general, abstract class with few or all methods being implemented, is much better than having an interface which has no methods implemented at all. This is based on the assumption that you are using it as a single inheritance.
Consider something similar to the NVI pattern (not sure what you'd call it in Java):
public abstract class A {
public final void doSomething() {
System.out.println("required");
doOptional();
}
protected void doOptional() {
System.out.println("optional");
}
}
public class B extends A {
#Override
protected void doOptional() {
System.out.println("overridden");
}
}
For your public API, you only expose a public final method which cannot be overridden. It performs some required work inside there and an optional method. When extending this class, you can only override doOptional().
Calling B.doSomething() will always print "required" before it proceeds.
Since doOptional() is not abstract, there's no purely code reason that class A needs to be abstract. But it might be desired for your particular project. For example, a base service that is always extended into specific sub-projects.
This can be useful for cases when the classes derived from the abstract base class must have some behaviour that is different from each other but that behaviour can not be abstracted as residing within a method that has the same signature for all the classes. Being unable to share a signature can occur if the different behaviour requires methods that are passed different primitive types. Because they use primitive types you can not use generics to express the similarity.
An abstract base class without any abstract methods is acting a bit like a marker interface, in that it is declaring that implementing classes must provide some behaviour without having that behaviour encapsulated within a new method with a signature that is the same for all implementations. You would use an abstract base class rather than a marker interface when the implementing classes have some behaviour in common, especially if the base class can implement it for the derived classes.
For example:
abstract class Sender {
protected final void beginMessage() {
...
}
protected final void endMessage() {
...
}
protected final void appendToMessage(int x) {
...
}
}
final class LongSender extends Sender {
public void send(int a, int b, int c) {
beginMessage();
appendToMessage(a);
appendToMessage(b);
appendToMessage(c);
endMessage();
}
}
final class ShortSender extends Sender {
public void send(int a) {
beginMessage();
appendToMessage(a);
endMessage();
}
}
It can be useful if you consider it an utility class.

Implementing interface with just one class or more classes

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.

how to instance generic abstract class

I am trying to profile a ann algorithm written in Java that is implemented as a generic abstract class and I cant figure out how to instance it.
Eclipse gives me error "Cannot instantiate the type KdTree" which is not very helpful. Any ideas on how to instance this class so I can test it?
Class defination and constructor:
public abstract class KdTree<T> {
private KdTree(int dimensions, Integer sizeLimit) {
this.dimensions = dimensions;
}
}
My attempt to instance it:
public class test_robo {
public void run_test()
{
KdTree<Integer> tree = new KdTree<Integer>(1,1);
}
}
link to the full code for KdTree
http://robowiki.net/wiki/User:Rednaxela/kD-Tree
First of all, you cannot instantiate an abstract class.
I saw the code in the link you provided; there are few implementations of the base class KdTree<T> already in there.
WeightedSqrEuclid
WeightedManhattan
...
If that's not what you're looking for, extend the base class and implement all those abstract methods as you wish.
You cannot instantiate an abstract class directly. The reason it is declared abstract is that it is not meant to be used by itself - you have to provide an implementation of its abstract methods first.
You need to inherit your own class from the abstract base, implement its abstract methods, and then instantiate your class. An instance of your class is automatically an instance of its abstract base.
public class ProfilerTree extends KdTree<Integer> {
public ProfilerTree(int dimensions, Integer sizeLimit) {
super(dimensions, sizeLimit);
}
...
// Implement abstract methods of KdTree<Integer> here
}
...
KdTree<Integer> tree = new ProfilerTree(1,1);
you can't instantiate an abstract class. Abstract actually means it doesn't make sense on its own so it always has to be extended and its methods implemented.
Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.
Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.
By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).
see http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
You can instantiate it by constructing an anonymous subclass, like so:
KdTree<Integer> tree = new KdTree<Integer>(1,1)
{
#Override
public void myAbstractMethodName()
{
//do something!
}
};
Otherwise, you can generate your own implementation:
private class KdTreeSub extends KdTree<Integer>
{
public KdTreeSub()
{
super(1, 1);
}
}
And later call it
public void myMethod()
{
...
KdTree<Integer> kdtree = new KdTreeSub();
...
}
The reason for this is that abstract classes are not complete classes. They are missing parts of them, usually a method. This method is marked with the "abstract" identifier:
public abstract int read();
The idea behind this is that you can construct a class that handles other parts:
public byte[] read(int len)
{
byte[] b = new byte[len];
for(int i = 0; i < b.length; i++) b[i] = read();
return b;
}
And simplify creating new classes.
The class, as it stands, was not meant to be instantiated. It's meant to store boilerplate code for concrete implementations. There are 4 of them in your link, starting with WeightedSqrEuclid.
You can either instantiate those, simply by e.g. new WeightedSqrEuclid<Integer>(1,1), or, if you want to profile the general code, write your own class extending KdTree.
However, in the latter case you should either create your subclass in the same file, or change a constructor of KdTree to at least protected. This is because, to create a subclass of this type, you need to call one of the constructors of KdTree in your implementation.

Categories