All -
I am currently studying for the OCA exam, and I'm using the OCA/OCP
Java SE 7 Programmer I & II Study Guide book, and I'm also
testing my knowledge with Enthuware.
I've only made it through Chapter 1 in the book, but I really thought I had a VERY good understanding of the topics discussed, which included the use of Access Modifiers.
In the book, on pages 19 - 20, it say "A class declaration with the public keyword gives all classes from all packages access to the public class. In other words, all classes in the Java Universe (JU) have access to a public class. Don't forget, though, that if a public class you're trying to use is in a different package from the class you're writing, you'll still need to import the public class.".
Based on that statement, my understanding was the following:
Class Access Modifier | Package | Can a different class in same package access this? | Can a different class in a different package access this? |
---|
none/default | none/default | Y | N |
public | none/default | Y | Y |
So then I ran into the following question on Enthuware that contradicts that rule.
I chose answers 2, 3 and 4. Answer 4 was incorrect, with their explanation "Remember that you can never access a class that is defined in the default package (i.e. the package with no name) from a class in any other package. So if you remove the package statement from Logger, you can't access it from util package, which is where TestClass is.".
I was really surprised that my answer was wrong, and even more surprised by Enthuware's explanation.
I know that you can explicitly define a public class in the default package, obviously without the use of the package statement, but Enthuware said that a different public class in a different package can't access the public class in the default package.
Based on that, it seems that the following is more correct:
Class Access Modifier | Package | Can a different class in the same package access this? | Can a different class in a different package access this? |
---|
none/default | none/default | Y | N |
public | none/default | Y | N |
public | non-default | Y | Y |
So what I THINK the book should have said is "for public classes is "A class declaration with the public keyword
in a non-default package gives all classes from all
non-default packages access to the public class. In other words,
all classes in the Java Universe (JU) have access to a public class. Don't forget, though, that if a public class you're trying to use is in a different package from the class you're writing, you'll still need to import the public class.".
I'm also wondering if the rules I thought I knew for protected methods will need to be adjusted in my mind due to this. I know protected methods can be inherited even if they're in different packages, but maybe that doesn't hold true if the class containing the protected methods is in the default package.
Thoughts? Is my second table more correct than the first?