简体   繁体   中英

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?

How about try using interface instead?

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

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

When you want to implement this interface:

for example one:

public class exampleOneClass implements newInterface {
     public void exampleOneMethod(int number) {
         newInterface.super.exampleOneMethod(number)
     }
}

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

You would need to extend it into two separate further classes, one with, the other without. extend is only for sharing common code, if it is not common code then it is not an implementation fit for inheritance, which is why composition is generally favored over inheritance .

Either put the additional manipulation into an abstract method and do it there, extending the class twice and leaving the method empty in one or just having exampleOneMethod implemented by two separate extending classes. Alternatively, redesign to make it fit for inheritance or redesign to make it use composition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM