Kacy Raye
Kacy Raye

Reputation: 1322

What is the difference between explicitly writing public and not writing public?

I thought there was no difference but then I encountered this:

public class Whatever
{

 String toString()  
{
//stuff
}

}

This code results in the compiler error:

toString() in Whatever cannot override toString() in java.lang.Object; attempting to assign weaker access privileges; was public

If I explicitly type public String toString() the code compiles just fine.

Upvotes: 0

Views: 269

Answers (3)

devang
devang

Reputation: 5516

In inheritance, when overriding methods you cannot narrow down access scope of a method. Here, the toString() method from Object class has public access and your class Whatever is trying to narrow down it's scope by changing access level to package (equivalent to no access modifier is specified) and this is not allowed.

A package level method can be defined as

void someMethod () {
}

If you see here, there is no access modifier before void, i.e. public, protected or private which implies all classes that are in the same package as Whatever will be able to access it. Any package outside of the package will not be able to access this method, not even a subclass of Whatever.

When you explicitly write public, entire would can use it at will.

Upvotes: 0

Hunter McMillen
Hunter McMillen

Reputation: 61512

If you don't use the public access specifier for methods and fields, they are assumed to be under package-level visibility.

Here is a nice diagram of what package and public mean in terms of visibility outside of your class:

Modifier       Class    Package   Subclass  World
----------------------------------------------------------
public           Y         Y         Y        Y       
protected        Y         Y         Y        N
no modifier      Y         Y         N        N       <--- This is package level
private          Y         N         N        N

Y means that the method, class, or field is visible.

N means that the method, class, or field is not visible

Upvotes: 5

AlexR
AlexR

Reputation: 115328

@Hunter McMillen mentioned the package level visibility (+1).

I just want to add a brief explanation what does it mean. It means that classes from the same package and sub classes of current class even if they themselves belong to other package can access this method/field.

Upvotes: 0

Related Questions