javanewb2.0 javanewb2.0 - 5 months ago 8
Java Question

Java Abstract Class with two nearly identical methods

I have created an Abstract class and am now combining the code from two different classes into it. Both the codes are similar, but with one line difference. How do I create the Abstract method with the similar portions, but differentiate for the one class that has an extra line of code?

For example:

public void exampleOneMethod(int number) {
***userChoice = choice - 2;***
while (userChoice.getNumber(number) == 0) {
number--
}
option = false;
}

public void exampleTwoMethod(int number) {
while (userChoice.getNumber(number) == 0) {
number--
}
option = false;
}

public void abstractMethod(int number) {
while (userChoice.getNumber(number) == 0) {
number--
}
option = false;
}


How do I put userChoice = choice - 2; into the abstract class only when example1 is extending the abstract class?

Answer

How about try using interface instead?

public interface newInterface {
    default void exampleTwoMethod(int number) {
        while (userChoice.getNumber(number) == 0) {
            number--
        }
    option = false;
    }
    void exampleOneMethod(int number);
}

When you want to implement this interface:

for example one:

public class exampleOneClass implements newInterface {
     public void exampleOneMethod(int number) {
         while (userChoice.getNumber(number) == 0) {
             number--
         }
     option = false;
     }
}

for example two:

public class exampleTwoClass implements newInterface {
    public void exampleTwoMethod(int number) {
        newInterface.super.exampleTwoMethod(number)
    }
}

It is a bit awkward to do this, as Tim suggested in the comment, you may need to consider rebuilding your class hierarchy.

For more information about default method in Java, please refer to this link. https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html

Comments