Define and execute partial functions of an interface - java

I am new to Java so i have some obvious (to some of you) questions about declaration, definition and execution of some functions.
Suppose you have declared two methods in an interface and you want to define the behavior of the first function in a (abstract?) class and the second function in another (abstract?) class.
Is there a way to define two methods in two separate classes? For example i could have a lot of methods in an interface but I want to implement just one of them because a specific object does not needs the others. How can I do that??
Java Code example :
interface DeclareFcnts {
void foo1();
void foo2();
}
abstract class Define_fcn1 implements DeclareFcnts {
public void foo1() {
// TODO Auto-generated method stub
}
}
abstract class Define_fcn2 implements DeclareFcnts {
public void foo2() {
// TODO Auto-generated method stub
}
}
class Myclass {
public static void main(String args[]) {
// How can i create an object that reference to the first function only?
}
}

If you implement an interface in a class, you must assume it will have all the interface methods declared. You must define what happens if any of these methods are invoked. Consider this:
DeclareFcnts instance = new Define_fcn1();
instance.foo2(); // what happens here?
What is your expected behavior on the second line? It could throw an exception, do nothing, (or return a value if the method wasn't void).
One option is to define the behavior in the concrete implementing class (because you cannot instantiate abstract classes), which is what you would like to avoid. Fortunatelly, in Java 8, there is another way - using default methods:
interface DeclareFcnts {
default void foo1() { /* default implementation, e.g. throw or do nothing */ }
default void foo2() { /* default implementation, e.g. throw or do nothing */ }
}
class Define_fcn1 implements DeclareFcnts {
public void foo1() { /* do something */ }
}
In this case, Define_fcn1 will inherit implementation of foo2 from DeclareFcnts much like if it inherited from a super class. You can notice that the class no longer needs to be abstract.
That said, you should try to avoid such situations. They will make unit testing, refactoring, etc., more difficult. You may possibly split your interface into multiple interfaces. If you need both methods somewhere, you can pass the interfaces separately, or, if absolutely necessary, define another interface like this:
interface Foo1Iface { void foo1(); }
interface Foo2Iface { void foo2(); }
interface BothIface extends Foo1Iface, Foo2Iface { }
I would avoid it if possible, though. You may get more suggestions if you add more details to your answer.

AFAIK it is not possible, when you are implementing an interface you are obliged to #override those methods in that interface but you can leave it as blank assuming that you would not call it. Although:
This is your Generic interface, it can be anything as long as you meet the requirements.
Credits to Pinterest.
If you are going to design a house it does not make sense to add a wheel or anything unrelated to the house. Otherwise create a separate Interface for a Car or a Bus.
An Example of Bad Design
interface GenericInterface{
public void defineDoor();
public void defineWindow();
public void defineWheel();
}
The actual implementation
class House implements GenericInterface{
#Override
public void defineDoor{
// do something
}
#Override
public void defineWindow{
// do something
}
#Override
public void defineWheel{
// does not make sense to the House.
}
}
Here is another class that implements the Generic Interface
class Car implements GenericInterface{
#Override
public void defineDoor{
// do something
}
#Override
public void defineWindow{
// do something
}
#Override
public void defineWheel{
// do something.
}
}
Though our Car fits the above Interface but since when did the House contains a wheel?. The right way to do this is to create Separate Interface for Car and House.

You can not do this!
you must declare body for your method that declared in interface and then create instance of class
or you can use java 8 default declaration for your interface methods

for example:
public interface IX
{
void sayHello();
void sayBye();
default void showInfo()
{
System.out.println("you call show Info method");
}
}

Related

How to override methods with different arguments?

I have several subControllers like below. I want to force developers to override run methods based on their needs. I mean all classes that extends MainController must override either run() or run(String command) methods. Is there any way to do this?
I have a base class called MainController
public abstract class MainController{
public abstract void run();
public abstract void run(String command);
}
public class Sub1Controller extends MainController{
public void run(){ //Some Codes Here }
public void run(String command) {} //empty method here
}
public class Sub2Controller extends MainController{
public void run(){} //empty method here
public void run(String command) { //Some Codes Here }
}
EDIT: Above example nearly solves my problem but I don't want to put empty methods everywhere.
You can't force a developer to implement one abstract method without having to implement others as well. You can provide empty default implementations though and let the dev override when needed:
//making the class abstract forces the dev to subclass it but not to override any method,
//which might not be necessary anyways.
public abstract class MainController{
public void run() { }
public void run(String command) {}
}
public class Sub1Controller extends MainController{
#Override
public void run(){ /*override only this method*/ }
}
Forcing a developer to only override one method but not the other isn't really possible at all. The problem is that every concrete class needs to implement every method and thus you have to provide implementations - either by providing them by default or by forcing the developer to provide them even if they're not needed.
However, your question indicates a design flaw: if the dev would only be required to implement one of those methods how would you make sure the correct one (the one that's being called) is overridden? You could theoretically call both but how would you prevent the dev from providing implementations for / overriding both methods?
Thus a different design might be better suited. Proposing one is hard though without knowing more of the context. One way might be to provide only one method that takes a parameter object that represents all possible parameters and let the dev decide which parameters to use. Another option might be to use multiple interfaces (each containing one method) and let the dev implement those (albeit they could still implement multiple interfaces in the same class).
Example of option 1 (one method only) using generics:
public interface Command {}
public interface MainController<T extends Command> {
public void run( T command );
}
public class Sub1Command implements Command { ... }
public class Sub1Controller implements MainController<Sub1Command> {
public void run( Sub1Command command ) { ... }
}
In the example I'm using generics to define the type of command parameter being passed. Thus the implementation can define which type of commands the run() method should accept (calling might be a bit more complex but again the context is missing).
To support a method similar to run() you could provide an empty implementation like VoidCommand implements Command and then Sub2Controller implements MainController<VoidCommand>.
The question is: Why do you need both versions of that method in your interface?
I suspect that this is w wrong understanding of ease of use.
The much more convenient solution would be to provide a special NO_COMMAD constant for the cases the command is not needed:
public interface MyInterface {
public static final String NO_COMMAD = "";
public void run(String command);
}
This solves your problem of having alternative method signatures.
The even betetr possibility would be to create different interfaces where one has a parameter in the methos signature and the other has not:
public interface MyInterfaceWithParam {
public void run(String command);
}
public interface MyInterfaceWithoutParam {
public void run();
}

How to force a subClass to implement a method in superClass which has body

Class Base{
public void doThings(){
//some logic that needed by subclass
}
}
Class A extends Base{
public void doThings(){
super.doThings();
doOtherThings();
}
}
What I want is to force A to overwrite doThings() method(there will be error message if not) and call super.doThings(); but doThings() in Base should not be abstract for it has body.
Is there any decent solutions? I found the same question in below link but the accepted answer does not answer it right.
Force SubClasses to #Override method from SuperClass. Method in SuperClass must have body
If you want to make sure that doThings of the base class is called, you should design your class like this:
abstract class Base {
public void doThings() {
// do some things here
...
// make sure subclass does some things too
methodYouMustImplement();
}
abstract void methodYouMustImplement();
}
class A extends Base {
#Override void methodYouMustImplement() {
// do some other things
}
}
This way, A is forced to give a implementation of methodYouMustImplement() and it is guaranteed by design that your code in doThings() is called without the need to remember to call super.doThings().
You could then consider making doThings() final, as Andy Turner suggested.
I think it would be easier to use a construct such as:
public class Base {
public void doStuff() {
doSpecificStuff();
// do base stuff every one has to do
}
abstract void doSpecificStuff();
}
public class WeirdlySpecific extends Base {
public void doSpecificStuff() {
// specific stuff happens
}
}
This does not force WeirdlySpecific to actually implement the doStuff() method, but as long as doStuff() is called as a contract by any caller, each more specific implementation has its own version of events.
A requirement to call the super method is considered an anti-pattern; that aside, the only way you can force a subclass to implement a method is to make it abstract.
If you want super.doThings() to be called first, and then subclass-specific stuff to be run after, turn the problem around:
Make doThings() final
Add an abstract method that is called within doThings().
Something like this:
abstract class Base {
public final void doThings() {
methodYouMustImplement();
// Stuff after subclass-specific implementation.
}
abstract void methodYouMustImplement();
}
class A extends Base {
#Override void methodYouMustImplement() {
doOtherThings();
}
}
The fact that doThings() is final is important to the requirements: this guarantees that the things you want to happen when doThings() is invoked, because no subclass can change this method. If you leave it non-final, subclasses can decide to override doThings(), meaning that methodYouMustImplement() (and any other actions you specify in doThing()) are not necessarily called.

Partial implementation of an abstract method?

For example, I have many classes that all need a certain method.
In this method, all these classes need one line of code, the remainder of the method is different.
How could I achieve something like this:
void method(){
everybodyDoesThisStuff;
// more individual stuff
// more individual stuff
}
Abstract methods cannot have a body, and if you were not to make it abstract you would then override the method and lose it.
You should make the method that does the "more individual stuff" abstract, not the method itself.
// AbstractBase.java
public abstract class AbstractBase {
public final void method() {
everybodyDoesThisStuff();
doIndividualStuff();
}
abstract void doIndividualStuff();
private void everybodyDoesThisStuff() {
// stuff that everybody does
}
}
// ConcreteClass.java
public class ConcreteClass extends AbstractBase {
void doIndividualStuff() {
// do my individual stuff
}
}
One solution is to require all subclasses to call super.method(). The problem is that there's no way to actually enforce that. Another option is to create a separate method that internally executes the required line and then calls an abstract method:
public final void method() {
callEveryTime();
doMethod();
}
protected abstract void doMethod();
Note that method() is public final so it can be called anywhere but not overridden, whereas doMethod() is protected so it can be overridden but not called outside its package (or subclasses).
You can make a normal method call an abstract method:
void foo(){
// do stuff
bar(); // let the abstract method do the rest
}
abstract void bar();
If you're asking yourself whether you need partial implementations of an abstract method, it's usually time to reconsider the granularity of your design.
Why not extract everybodyDoesThisStuff into a separate method and put it in an Interface?

Provide implementation for abstract method but restrict visibility

I have a method in an abstract class that calls an abstract method, for which the subclasses must provide the implementation.
public abstract class AClass {
public void foo() {
...
fooToImplement();
...
}
// DON'T CALL THIS METHOD, ONLY PROVIDE IMPLEMENTATION!
protected abstract void fooToImplement();
}
I want to make sure that the subclasses don't call fooToImplement(), they should always use foo() instead. The behavior is something like a "private abstract" method, but that's not possible in Java.
Is there some alternative? Thanks!
If you don't want your subclasses to be able to call this method you could use strategy: Extract the behavior of the method into an interface and pass an implementation of this interface to the object. E.g.
IStrategy {
public void fooToImplement();
}
AClass {
public AClass(IStrategy impl) {...}
public void foo() {
...
strategy.fooToImplement();
...
}
}
Delegation instead of inheritance. In java 8 this would be a little bit easier.
If your implementation of IStrategy would need access to the data of the object AClass, you could try to implement it as an inner class.
The method has to be visible by your subclass if you want it to be overriden.
You have to use a class witch does not extends AClass as caller.
public class BClass extends ACLass {
#Override
protected void fooToImplement() {
System.out.println("override me im famous");
}
}
public class CClass {
private BCLass bInstance;
public void doSomething(){
bInstance.foo();
// !!! NO ACCESS TO fooImplement()
}
}
Since fooToImplement() needs to be visible to subclasses to be implemented there and there's no way to distinguish between "implement visibility" and "execution rights", you can't do this by inheritance.
You could however combine your object with another object that contains fooToImplement() by composition:
interface FooImplementation {
void fooToImplement(AClass a);
}
public abstract class AClass {
private final FooImplementation fooImpl;
protected AClass(FooImplementation fooImpl) {
this.fooImpl = fooImpl;
}
public void foo() {
...
fooImpl.fooToImplement(this);
...
}
}
That wouldn't prevent anyone from outside the class from using yourFooImpl.fooToImplement(yourAClass) however. To prevent this you could create a class that provides the information that fooToImplement() needs, but that can only be instanciated from within AClass:
interface FooImplementation {
void fooToImplement(AClass.AClassFooView a);
}
public abstract class AClass {
private final FooImplementation fooImpl;
protected AClass(FooImplementation fooImpl) {
this.fooImpl = fooImpl;
}
public class AClassFooView {
...
private AClassFooView() {
}
}
public void foo() {
...
fooImpl.fooToImplement(this.new AClassFooView());
...
}
}
But fooToImplement could pass the reference to AClassFooView to other classes...
However depending on the implementors of your class making absolutely sure in the documentation, that nobody should call fooToImplement() could also be an alternative.
Ultimately you have to trust the implementors, since there's also the the possibility of someone using reflection to get access to private members, reverse engeneering+changing+recompiling your class ect..
You can use AOP to this, for example add aspect #Before to fooToImplement() and check stacktrace of calling and throw IllegalArgumentException if fooToImplement() be called any method except foo(), something like:
if(!Thread.currentThread().getStackTrace()[1].getMethodName().equals("foo")) {
throw new IllegalArgumentException("You musn't call fooToImplement() directly"+
", using foo() instead");
}
However this way has two problem:
perfomance
runtime exception

How to hide method of parent interface in Java?

I have 3 classes.
public interface Operation {
void move();
void delete();
void search(String criteria);
}
public abstract class AbstractOperationProcessor implements Operation {
public void move() {
// some logic
}
}
public class DailyMailProcessor extends AbstractOperationProcessor{
// need to hide this method because I don't want to provide them to customer
public void delete() {}
public void search(String criteria) {}
}
What I need is to hide methods delete() and search(String) from API. How can I do it without changing interface Operation and abstract class AbstractOperationProcessor?
You cannot. The best you can do is implement stubs that throw something like NotImplementedException and document this fact.
I would use this as an opportunity to examine the definition of the top-level interface. If you need to hide some of its methods then the real problem may be that it aggregates unrelated functionality. You may need to split it into two separate interfaces.
Remember, you can "inherit" (i.e. implement) multiple interfaces.
As the other answers already stated: You cannot hide a method of a superclass. There is also a good reason that you cannot do this: Polymorphism allows you to pass any object of a subtype where an object of a supertype is needed. In your case, if you have a method
void foo(Operation op){op.delete()}
you can call
foo(new DailyMailProcessor())
As you can see, foo does not know the exact type of op, but because delete is in Operation's interface, the method delete can be called.
If you happen to want to remove some methods from a subtype's interface, you are probably not implementing a behavioral subtype! I suggest you have a look at the Liskov Principle, which is one of the fundamental principles in object oriented programming.
If, what you have is not a behavioral subtype, you are wrongly trying to achieve code reuse by inheritance. You should use composition instead. Favor composition over inheritance (Item 16, Effective Java). The reason to favor composition in your case is obvious: You do not have to throw an UnsupportedOperationException (as mentioned in the other answers) and hereby gain static safety.
Edit: To clarify what I mean when telling you to use composition: Instead of having class DailyMailProcessor extending Operation, give it an member variable of type Operation and forward calls to the methods you want to support to the member variable.
public interface Operation {
void move();
void delete();
void search(String criteria);
}
public class DailyMailProcessor {
private Operation op;
public DailyMailProcessor {/*instantiate op*/}
void move() {op.move();}
}
You cannot do that. Every method declared in the interface should be implemented by the class. What you can do is you just implement those methods but do not give any definition to it.
Edit:
As suggested in the comments, UnsupportedOperationException might be a better choice.
Original answer:
There is the IllegalStateException just for that. Just make all the methods you don't want to implement throw that. Just do:
public class DailyMailProcessor extends AbstractOperationProcessor {
public void delete() {
throw new IllegalStateException();
}
public void search(String criteria) {
// do something useful here
}
}
the best solution that handle your probleme, if, and only if you want to have it in an elegante way, is to use a component system and it would look some this like that:
abstract class Component {
abstract void perform();
}
abstract class Move extends Component {
void perform() { ... }
}
class AbstractOperationProcessor {
List<Component> components;
...
}

Categories