1
I just took a test and I found a suspicious question, I’d like your opinion.
In the Java programming language, when the method of a class
does not have an explicitly declared access modifier means that this method can be accessed(A) for all classes of the same package in which it was declared.
(B) by any class other than belonging.
(C) by the class to which it belongs, exclusively.
(D) by the class in which it was declared and its subclasses, and by members other classes in the same package.
I think the D answer is correct, including in a test I did the method behaved normally and without any problem at compile time and at runtime:
class Teste {
String teste() {
return "ola";
}
}
class Teste2 extends Teste {
}
class Principal {
public static void main(String[] args) {
Teste2 t = new Teste2();
System.out.println(t.teste());
}
}
The preliminary feedback informs that the correct answer is (A).
You’re right, it’s the same letter A. No access modifier, any class member is accessible by all classes that are in the same package.
– user28595
Try to do the same test you did by creating 2 files from different classes and no inheritance, but within the same package.
– user28595
If you want something more concrete and official, see the explanatory table in the oracle documentation: https://docs.oracle.com/javase/tutorial/javaO/accesscontrol.html
– user28595
@diegofm then the mistake are in claiming that I have access to the subclasses? From what I understand, I may have access to subclasses but as long as these are in the same package ne? If I have different packages I can’t use herence... I think I fell for a little haha so I think the option would be correct only if I informed that it was the subclasses but belonging to the same package.
– Ygor Magalhaes
Exactly that, standard modifier restricts access to members of an A class only to other classes that share the same package, regardless of whether there is inheritance or not. So much so that in the table it even shows that even if a class B inherits from A but is out of the same package, even if it is "daughter" it will also not see default members. ->
The third column indicates whether subclasses of the class declared outside this package have access to the member.
– user28595
Thanks for the help! I just tested here and saw that it really doesn’t work.
– Ygor Magalhaes
Why don’t you create an answer to get better recorded?
– Rafael B.