Java Reference
In-Depth Information
You can also use the keyword this to qualify an instance method name, although it is never required. The
following snippet of code shows the m1() method invoking the m2() method using the keyword this . Note that both
methods are instance methods and they could use the simple name to invoke each other.
public class ThisTestMethod {
void m1() {
// Invoke the m2() method
this.m2(); // same as "m2();"
}
void m2() {
// do something
}
}
Access Levels for Class Members
I have covered access levels for a class, which can be public or default (or package level). This section discusses access
levels for class members: fields and methods. The access level for a class member determines what area of the program
can access (use or refer to) it. One of the following four access level modifiers can be used for a class member:
public
private
protected
Default or package-level access
Three out of the four types of access levels for a class member are specified using one of the three keywords:
public , private , or protected . The fourth type is called the default access level (or package-level access), and it is
specified by using no access modifiers. That is, the absence of any of the three access level modifiers, public , private ,
or protected , specifies package-level access.
If a class member is declared as public using the public keyword, it can be accessed from anywhere in Java code,
provided the class itself is accessible.
If a class member is declared as private using the private keyword, it can be accessed only within the body of the
declaring class, and nowhere else.
If a class member is declared as protected using the protected keyword, it can be accessed from the same
package or from descendants of the class, even if the descendants are in a different package. I will discuss the
protected access level in detail in the chapter on inheritance.
If you do not use any access level modifier for a class member, it has package-level access. A class member with a
package-level access can be accessed from the same package.
Access levels for a class member can be listed from the most restrictive to the least restrictive as private ,
package-level, protected , and public . Table 6-3 summarizes the four access levels for a class member.
Table 6-3. List of Access Levels for Class Members
Access Level for Class Member
Accessibility
private
Only within the same class
package-level
In the same package
protected
Same package or descendant in any package
public
Everywhere
 
 
Search WWH ::




Custom Search