Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the default access modifier in Java? [duplicate]

What is the default access modifier for a method or an instance variable if I do not state it explicitly?

For example:

package flight.booking;

public class FlightLog
{
    private SpecificFlight flight;

    FlightLog(SpecificFlight flight)
    {
        this.flight = flight;
    }
}

Is the access modifier of this constructor protected or package? Can other classes in the same package, which is flight.booking, call this constructor?

like image 992
yrazlik Avatar asked Oct 07 '22 18:10

yrazlik


People also ask

Which is the default access modifier in Java?

The default access modifier is also called package-private, which means that all members are visible within the same package but aren't accessible from other packages: package com.

What is the default access specifier in Java class?

The default visibility is known as “package-private” (though you can't use this explicitly), which means the field will be accessible from inside the same package to which the class belongs.

What are the 3 access modifiers?

As previously mentioned, there are three access modifiers: public , private , and protected .

What is the default access modifier in a class?

Class, record, and struct accessibilityinternal is the default if no access modifier is specified. Struct members, including nested classes and structs, can be declared public , internal , or private .


2 Answers

From documentation:

Access Levels
Modifier        Class    Package    Subclass    World
-----------------------------------------------------
public           Y        Y          Y           Y
protected        Y        Y          Y           N
(Default)        Y        Y          N           N
private          Y        N          N           N
like image 44
Pradeep Avatar answered Oct 12 '22 18:10

Pradeep


From Java documentation

If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes — you will learn about them in a later lesson.)

At the member level, you can also use the public modifier or no modifier (package-private) just as with top-level classes, and with the same meaning.

Full story you can read here (Which I wrote recently):

http://codeinventions.blogspot.com/2014/09/default-access-modifier-in-java-or-no.html

like image 178
Suresh Atta Avatar answered Oct 12 '22 18:10

Suresh Atta