Page 1 of 1

About Question enthuware.ocpjp.v7.2.1334 :

Posted: Thu Nov 21, 2013 12:48 pm
by marcel
I am sorry,
but I think your explanation is not exactly correct.
Now, you may think that the actual object is of class B and method is selected according to the actual object. This is true but access rights are checked at compile time.
For private methods the quoted explanation is not true, private Methods are selected at compile time and not invoked dynamically, so private methods technically cannot be overridden.
This example shows it:

Code: Select all

public class AccessPrivateTest {

	public static void main(String[] args) {
		B b = new B();
		b.invokePrint();
	}

}

class A {
	private void print() {
		System.out.println("A");
	}
	
	public void invokePrint() {
		print();
	}
}

class B extends A {
	public void print() {
		System.out.println("B");
	}
}
If your statement was true, "B" would be printed, but in fact "A" is printed.
Best regards
Marcel

Re: About Question enthuware.ocpjp.v7.2.1334 :

Posted: Thu Nov 21, 2013 1:46 pm
by admin
It is true that private methods are not inherited (and hence cannot be overriden), but that is not really the issue in this question. The issue here is of the access rights (not of inheritance/overriding). The explantion is trying to point out why a reader might think that the given code will compile. It is in this context it makes the statement you referred to. What it really means to say is this:
Now, you may think that the actual object is of class B and method is selected according to the actual object. Generally, this is true, but access rights are checked at compile time.
The statement is not meant to be factual statement on its own out of context but only trying to explain a point.

Nonetheless, you are right that the statement is not entirely correct and should be fixed asap.

thank you for your feedback!
Paul.