Access modifier for Java methods - Default

Asked

Viewed 262 times

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).

  • 1

    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.

  • Try to do the same test you did by creating 2 files from different classes and no inheritance, but within the same package.

  • 1

    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

  • @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.

  • 1

    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.

  • Thanks for the help! I just tested here and saw that it really doesn’t work.

  • 1

    Why don’t you create an answer to get better recorded?

Show 2 more comments

1 answer

1

One answer just for the record:

The answer is the letter A. If you have no access modifier specified, then the access is package(package).

If a subclass is in another package, will not have access/visibility the method or property of the Parent class with access modifier equal to package.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.