Java inheritance with abstract method - java

I have a lot of "form" classes all of which extend Form. I have an abstract class called FormService and specific form services that extend this class. What I want to do is have an abstract method called populate() which takes a type of form thus calling the correct service for the given type through inheritance.
So I have something like:
public abstract FormService {
public abstract void populate(Form form);
}
public TestFormService extends FormService {
public void populate(TestForm form) {
//populate
}
Where TestForm is a type that extends Form. Is this possible because I can't seem to get the affect I want.

You could use generics:
public abstract FormService<F extends Form> {
public abstract void populate(F form);
}
public TestFormService extends FormService<TestForm> {
#Override
public void populate(TestForm form) {
//populate
}
}
Note that the use of #Override here is just good practice, but unrelated to the question.

Yes this is possible. As while overriding a method in the the child class, can always use subclass of the super class declared as an argument in the parent class method. In this example as testForm is a subclass of Form class this will work. Thumb rule is while overriding we can always restrict the hierarchy but not widen the hierarchy.
Suppose parent class of Form class is Document. In TestFormService class populate method we can not use Document as an argument. This will violate overriding rules.

Related

How to force an interface to be present at all levels of inheritance

I have an interface myIf, that i would like to have present at all levels of inheritance. The idea is that fooEverywhere needs to be at GrandParent and Parent and further children. So this obvious pattern occurs:
public interface myIf {
void fooEverywhere ();
}
public class GrandParent implements myIf {
#Override
public void fooEverywhere() { /* Actions */ }
}
public class Parent extends GrandParent implements myIf {
#Override
public void fooEverywhere() { super.fooEverywhere(); /* And Other actions */ }
}
However, if i forget / miss Parent like this:
public class Parent extends GrandParent /*implements myIf*/ {
// #Override
// public void fooEverywhere() { super.fooEverywhere(); /* And Other actions */ }
}
Java, will still be OK, as parentObject.fooEverywhere() will find GrandParent.fooEverywhere().
Therefore how can i redesign this to force Java to recognise that fooEverywhere must be in Parent ?
The short answer is that you can't.
The longer answer is that you can't because you've already provided an implementation in a class higher in the inheritance chain. Once it's implemented higher in the chain, it's implemented.
You could create an abstract class as the ancestor which implements the interface and then declare the interface methods as abstract on the abstract ancestor. Then both GrandParent and Parent would then extend AbstractParent and have to provide their own implementations of the interface methods that were declared as abstract.
Note, interfaces in Java are typically Pascal-case, i.e. MyIf, not myIf. Also, there is no need to actually use the implements keyword in a descendent class that has a parent already declaring it implements an interface.
As you already said, the compiler does not care as long as as a superclass provides an implementation of the abstract or interface method.
I can hardly imagine any usecase where it it necessary to implement a method in every subclass, but if you really need it you can implement a solution using reflection with Class#getDeclaredMethods (only return the methods declared in this class) to validate if each of the classes implements or overrides the method. If not, throw an exception.

Override interface with different signature

I have the following problem:
an Interface with a simple listener, inerithed from a library:
public interface RequestListener<RESULT> {
void onRequestFailure(FooException fooException);
void onRequestSuccess(RESULT result);
}
a class who extends FooException:
public class MyCustomFooException extends FooException {
. . .
}
}
and I need to overload the signature of the onRequestFailure method with my custom class.
something like this:
public interface MyCustomListener<RESULT> extends RequestListener<RESULT> {
#Override
public void onRequestFailure(MyCustomFooException e);
#Override
public void onRequestSuccess(RESULT result);
}
how can i do that?
You could use another typed Parameter to your interface :
public interface RequestListener<RESULT,T extends FooException> {
void onRequestFailure(T fooException);
void onRequestSuccess(RESULT result);
}
Then when you implement your interface, you can define :
public interface IglooListener<RESULT> extends RequestListener<RESULT,MyCustomFooException> {
#Override
public void onRequestFailure(MyCustomFooException e);
#Override
public void onRequestSuccess(RESULT result);
}
You cannot do that (in a class). If you do it, you're no longer implementing the RequestListener interface. You need to use the exact same signature from the
interface: void onRequestFailure(FooException fooException);
If you do it in an interface and if you use another signature, you're extending the original interface by just adding a new method to it. If a non-abstract class later on implements the extended IglooListener interface, it will have to define both methods.
Just remove the #Override from the method in IglooListener interface. you will be good to go. In that case you will be having two methods in IglooListener one from the RequestListener and other one from the IglooListener. Hope this helps.
Unfortunately, this is not possible in Java because your inheriting class would narrow the possible input parameter types to a subset originally allowed and could therefore not behave like the original interfaced intended to.
EDIT Just like the other answers state, you can add a method with this signature, but it would not override the interface method.

What do you do when a subclass can't implement an interface method because the superclass has a final method with the same signature?

Let's say you have a class that extends Activity and implements MyInterface, where Activity contains public final void setProgress(int progress) and MyInterface contains public abstract void setProgress(int progress)
I need to override the method from the interface, but I can't because Activty says it's final and can't be overridden.
What do I do?
Example:
public class MyActivity extends Activity implements MyInterface
{
#Override
protected void onCreate(Bundle bundle)
{
//stuff goes here
}
//Cannot override the final method from Activity
#Override
public void setProgress(int progress)
{
}
}
Let's also extend this question and say you don't have access to the source of MyInterface to change it, what does one do in such situations?
Use a decorator Design Pattern.
and here's a simplified example of the decorator pattern.
(adapted from the interwebs and polygenelubricants' answer on SO)
Note: before we begin remove the abstract keyword from the interface, that's wrong syntax
The class hierarchy is restructured as static inner classes so that the whole example is contained in one compilation unit (as seen on ideone.com):
Here's a diagrammatic overview of intended class hierarchy
public class AnimalDecorator {
static interface Animal {
public String makeNoise();
public void wagTail();
//other methods
}
static class Dog implements Animal {
public final String makeNoise() { return "woof"; }
public final void wagTail() { //do wag tail action }
}
static class DogDecorator implements Animal {
//delegate
private Animal animal;
public DogDecorator (Animal animal){this.animal = animal;}
public String makeNoise() { animal.makeNoise();}
public void wagTail() { animal.wagTail();}
}
static class LoudDog extends DogDecorator {
#Override public String makeNoise() {
return "WOOF WOOF WOOF!!!";
}
}
}
So here we have a simple Animal hierarchy, with Dog subclass. We also have a DogDecorator decorator -- also an Animal -- that simply delegates all methods to another Animal. That is, it doesn't really do any effective decoration, but it's ready to be subclassed so that actual decorations can be added.
We only have two methods here, makeNoise() and wagTail(). We then create the class we want LoudDog and use it. (Consider the case where Animal has many methods; then Normal would be most valuable).
Note that we can even stack one decoration on top of another. The exact implementation details may vary, but this simplified example pretty much captures the essence of the decorator pattern.
Steps
Subclass the original "Component" class into a "Decorator" class (see UML diagram);
In the Decorator class, add a Component pointer as a field;
Pass a Component to the Decorator constructor to initialize the Component pointer;
In the Decorator class, redirect all "Component" methods to the "Component" pointer; and
In the ConcreteDecorator class, override any Component method(s) whose behavior needs to be modified.
See also
Effective Java 2nd Edition, Item 18: Prefer interfaces to abstract classes
Related questions
Interface vs Abstract Class (general OO)
Is it just me or are interfaces overused?
You cannot override the final method because in the Java programming language, the final keyword is used to define an entity which cannot later be changed.
form Java Language Specification
Never tried but can give it a try.
You must implement the MyInterface in subclass too and can override the setProgress method of MyInterface and not of its superclass.
Should say..a good question:)
Edit:
In this case, the class cannot override the final method. So either your interface will have the exact same signature as the parent class (hence the interface is implemented automatically by inheritance), or you create a method with a different name.
The solution would largely depend on the circumstances, there's no textbook solution here.
Don't have your MyActivity implement MyInterface and instead create anonymous or inner class that implements it.
This ways you still have access to all MyActivity components and functions from setProgress(int) which is completly separate from final Activity.setProgress(int).

not implementing all of the methods of interface. is it possible?

Is there any way to NOT implement all of the methods of an interface in an inheriting class?
The only way around this is to declare your class as abstract and leave it to a subclass to implement the missing methods. But ultimately, someone in the chain has to implement it to meet the interface contract. If you truly do not need a particular method, you can implement it and then either return or throw some variety of NotImplementedException, whichever is more appropriate in your case.
The Interface could also specify some methods as 'default' and provide the corresponding method implementation within the Interface definition (https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html). These 'default' methods need not be mentioned while implementing the Interface.
The point of an interface is to guarantee that an object will outwardly behave as the interface specifies that it will
If you don't implement all methods of your interface, than you destroy the entire purpose of an interface.
We can override all the interface methods in abstract parent class and in child class override those methods only which is required by that particular child class.
Interface
public interface MyInterface{
void method1();
void method2();
void method3();
}
Abstract Parent class
public abstract class Parent implements MyInterface{
#Override
public void method1(){
}
#Override
public void method2(){
}
#Override
public void method3(){
}
}
In your Child classes
public class Child1 extends Parent{
#Override
public void method1(){
}
}
public class Child2 extends Parent{
#Override
public void method2(){
}
}
I asked myself the same question, and then learned about Adapters. It solved my problem, maybe it can solve yours. This explains it very well : https://blogs.oracle.com/CoreJavaTechTips/entry/listeners_vs_adapters
You can do that in Java8. Java 8 introduces “Default Method” or (Defender methods) new feature, which allows a developer to add new methods to the Interfaces without breaking the existing implementation of these interfaces.
It provides flexibility to allow Interface define implementation which will use as default in the situation where a concrete Class fails to provide an implementation for that method.
interface OldInterface {
public void existingMethod();
default public void DefaultMethod() {
System.out.println("New default method" + " is added in interface");
}
}
//following class compiles successfully in JDK 8
public class ClassImpl implements OldInterface {
#Override
public void existingMethod() {
System.out.println("normal method");
}
public static void main(String[] args) {
ClassImpl obj = new ClassImpl ();
// print “New default method add in interface”
obj.DefaultMethod();
}
}
Define that class as an abstract class. However, you must implement those unimplemented methods when you want to create an instance of it (either by using a subclass or an anonymous class).
It is possible and it is easy. I coded an example.
All you have to do is inherit from a class that does implement the method. If you don't mind a class that is not instantiable, then you can also define an abstract class.
If you want an instantiable class, it is not possible. You may try to define an abstract class, though.
If you try to implement an interface and you find yourself in a situation where there is no need to implement all of them then, this is a code smell. It indicates a bad design and it violates Liskov substitution principle. Often this happens because of using fat interface.
Also sometimes this happens because you are trying to implement an interface from an external dependency. In this case, I always look inside the source code to see if there is any implementation of that interface which I can either use it directly or subclass it and override methods to my needs.
We can use Adapter classes ,which reduces complexcity by not making mandatory to implement all the methods present in the interface
Adapter class is a simple java class that implements an interface with only EMPTY implementation .
Instead of implementing interface if we extends Adapter class ,we provide implementation only for require method
ex--- instead of implementing Servlet(I) if we extends GenericServlet(AC) then we provide implementation for Service()method we are not require to provide implementation for remaining meyhod..
Generic class Acts as ADAPTER class for Servlet(I).
yes possible below shown is the way
interface Test {
void m() throws NullPointerException;
}
class Parent {
// Parent class doesn't implements Test interface
public void m() {
System.out.println("Inside Parent m()");
}
}
class Child extends Parent implements Test {
}
public class Program {
public static void main(String args[]) {
Child s = new Child();
s.m();
}
}

abstract class with abstract fields and subclassing without casting

I created an abstract base class. It contains an object which should be extended by any subclasses:
public abstract class AbstractParent {
protected AbstractObject subMePlz;
// ... some fields that all subclasses need
public AbstractParent() {
this.subMePlz = createThisInYourExtendedClass();
}
public abstract AbstractObject createThisInYourExtendedClass();
}
the abstractObject:
public abstract class AbstractObject {
// ... some fields/methods that all subclasses need
}
What I want is to be able to use the extended field in the extended class without casting:
public class ExtendParent extends AbstractParent {
// .. some unique fields
public ExtendParent(){
super();
}
public ConcreteObject createThisInYourExtendedClass(){
return new ConcreteObject();
}
// what I want to do - no cast
public void doSomethingWithSubMePlzWithoutCastingIt() {
System.out.println(this.subMePlz);
}
// what I end up doing - gotta cast
public void doSomethingWithSubMePlzWithoutCastingIt() {
System.out.println((ConcreteObject)this.subMePlz);
}
}
Would needing a comparator change how I should implement this? - I'm thinking a generic comparator for a list of the AbstractObjects that could be used by its subclasses.
It sounds like you need to make it generic:
public abstract class AbstractParent<T extends AbstractObject> {
protected T subMePlz;
// ... some fields that all subclasses need
public AbstractParent() {
this.subMePlz = createThisInYourExtendedClass();
}
public abstract T createThisInYourExtendedClass();
}
public class ExtendParent extends AbstractParent<ConcreteObject> {
...
}
Note that calling non-private methods within a constructor is usually a bad idea - the subclass won't have been fully initialized yet, which can make it difficult to reason about how much you can really rely on.
You have two options:
Abandon the project to declare the field in the superclass. Instead, add an internal abstract "getter" method to your superclass -- basically, AbstractParent should have a method abstract AbstractObject getSubMePlz().
Use generics to set the type of subMePlz in your subclass: define AbstractParent<T> to have a T for its subMePlz field.
Personally, I frequently find option 1 to be very pleasantly extensible -- for example, you can have another subclass that narrows the getSubMePlz() return type without yet declaring it, which can be advantageous.
Why not use this -
super.subMePlz
instead of this -
(ConcreteObject)this.subMePlz
That way, you won't need a cast.
You just could save a copy of the object in the subclass but with the correct class.
public class ExtendParent extends AbstractParent {
ConcreteObject concreteObject;
public AbstractObject createThisInYourExtendedClass(){
ConcreteObject concreteObject = new ConcreteObject();
return concreteObject;
}
public void doSomethingWithSubMePlzWithoutCastingIt() {
System.out.println(concreteObject);
}
...

Categories