Java Method Scopes

In this Java article we want to learn about Java Method Scopes, in Java method scopes determines where a method can be accessed within a program. understanding method scopes is important for writing code that is organized, easy to read and secure. so now let’s talk about this concept in details.

 

 

Types of Java Method Scopes

There are four different types of method scopes in Java: public, private, protected and package-private.

 

 

Java Public Methods

Public methods are methods that can be accessed from anywhere within a program, including other classes and packages. they are denoted by the public keyword in their method signature, in this example myPublicMethod is a public method that can be accessed from anywhere in the program.

 

 

Java Private Methods

Private methods are methods that can only be accessed within the same class in which they are defined. they are denoted by private Java keyword in their method signature, in this example myPrivateMethod is a private method that can only be accessed from MyClass class.

 

 

Java Protected Methods

Protected methods are methods that can be accessed from the same class, as well as any subclass and any other class in the same package. they are denoted by protected keyword in their method signature. 

 

 

Package-Private Methods

Package private methods are methods that can be accessed from the same package, but not from any other package. they are denoted by the absence of any access modifier in their method signature, in this example myPackagePrivateMethod is a package-private method that can be accessed from any class in the same package as MyClass, but not from any other package.

 

 

 

Learn More

Leave a Comment