Since Donkey's location field has default access modifier, ((Donkey)m).location from TestClass will generate a compile-time error. To fix this we can:
- Change Donkey's location access modifier to public
- Use reflection:
Code: Select all
// in file TestClass.java
package px;
import p1.Movable;
import p2.Donkey;
import java.lang.reflect.Field;
public class TestClass {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Movable m = new Donkey();
m.move(10);
m.moveBack(20);
Field donkeyLocation = m.getClass().getDeclaredField("location"); // retrieves Donkey's location field
donkeyLocation.setAccessible(true); // suppresses Java access control to make it readable
System.out.println(donkeyLocation.get(m)); //prints 190
}
}
- Move TestClass.java file to package p2 or Donkey.java file to package px