user9717641
user9717641

Reputation:

Creating common method for two classes not using inheritance in java

I'm just wondering if there is any way to create two classes that aren't related but have the same implementation of method. I know there are interfaces and static methods but it seems like they are good only when you have static field in class. Is this possible to do that kind of thing when method uses field that is specific to exact object? I know it's a bad practice writing code like this but I'm just curious.

EDIT: I mean something like this:

public class Person implements MakingOlder {
  private int age;
}

public class Cat implements MakingOlder {
  private int age;
}

public interface MakingOlder {
  public static void makeOlder() {
        this.age += 2;
  }
}

I don't want to make common base class for Person and Cat and interface is not working. I'm trying to avoid writing the same implementation twice and copying the code.

Upvotes: 1

Views: 2687

Answers (3)

Andriy Zhuk
Andriy Zhuk

Reputation: 143

Probably your interface is not working because you are trying to implement a method within the interface:

public static void makeOlder() {
    this.age += 2;
}

In order to make it work, try to add the default keyword so that it looks like:

default Integer makeOlder(Integer age) {
    age += 2;
    return age;
}

Then the class, which implements that interface, will just need to contain something like:

public class Dummy implements AA {

    Integer age;

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

To test the result you can call something like:

Dummy d = new Dummy();
d.setAge(d.makeOlder(7));
System.out.println(d.getAge());
d.setAge(d.makeOlder(d.getAge()));
System.out.println(d.getAge());

Upvotes: 0

Tristan
Tristan

Reputation: 9121

Sure, it's called "composition + delegation", and it's often a good practice to replace inheritance by this :

https://en.wikipedia.org/wiki/Composition_over_inheritance

public class Person implements AgingObject {
  private int age;  
  private AgingBehavior agingBehavior;

  void makeOlder() {
    agingBehavior.makeOlder(this);
  }
  //(...)
}

public class Cat implements AgingObject {
  private int age;
  private AgingBehavior agingBehavior;

  void makeOlder() {
    agingBehavior.makeOlder(this);
  }
  //(...)
}

public class AgingBehavior {
  void makeOlder(AgingObject agingObject) {
    agingObject.setAge(agingObject.getAge() + 2);
  }
}

public interface AgingObject {
    int getAge();
    void setAge(int age);
}

Upvotes: 4

Betlista
Betlista

Reputation: 10549

...or you can use default implementation in Java 8+...

public interface MakingOlder {

    public default void makeOlder() {
        setAge(getAge() + 2);
    }

    int getAge();

    void setAge(int age);

}

and of course your Person and Cat implements MakingOlder...

Upvotes: 3

Related Questions