1 2 3 | abstract public class StrictParent { abstract void punishChild(); } |
Then we define an interface ParentFace that declares a method punishChild() with exactly the same method signature as the method defined in StrickParent class
1 2 3 | public interface ParentFace { void punishChild(); } |
Now we have a class MyParent that is subclassed from StrictParent and implements the ParentFace. Notice that because the parent class and the interface declare the same method so it only need to override the method once.
1 2 3 4 5 6 7 8 | public class MyParent extends StrictParent implements ParentFace { @Override public void punishChild() { System.out.println("Kick in the ass!"); } } |
Let's test run our code.
The core idea here is that by defining an interface that declares methods the same as the parent class, you add a layer of abstraction. Instead of passing the parent class type in the method parameter, we can pass the interface now and it makes the code flexible. In the following example, we replace the variable mum with a mocked-up Object.
This technique is particularly useful in Unit Testing.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public class Main { public static void showMessage(ParentFace parent){ parent.punishChild(); } public static void main(String[] args) { // declare the type as the interface so that you can mock the Object later ParentFace mum = new MyParent(); showMessage(mum); // this time try to mock the MyParent mum = new ParentFace() { @Override public void punishChild() { System.out.println("pat on the back."); } }; showMessage(mum); } } |
The output of this program is:
Kick in the ass!
pat on the back.
No comments:
Post a Comment