About Question enthuware.ocajp.i.v7.2.1403 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

ftejada
Posts: 5
Joined: Mon Jan 28, 2019 2:00 pm
Contact:

Re: About Question enthuware.ocajp.i.v7.2.1403 :

Post by ftejada »

admin wrote:
Sun Feb 05, 2017 10:44 pm
To access's Donkey's location instance variable, cast your reference to Donkey first. Like so:
((Donkey)m).location
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

admin
Site Admin
Posts: 10058
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question enthuware.ocajp.i.v7.2.1403 :

Post by admin »

Correct. Reflection is not on the ocp exam, so you can leave that though.
If you like our products and services, please help us by posting your review here.

baichen7788
Posts: 23
Joined: Fri Mar 26, 2021 7:25 am
Contact:

Re: About Question enthuware.ocajp.i.v7.2.1403 :

Post by baichen7788 »

why it prints interface location=0 instead of location in object?

Post Reply

Who is online

Users browsing this forum: Google [Bot] and 112 guests