www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons Java Access Specifiers Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Each field and method in a class definition has an access level. Keywords private, protected and public are used to declare a field and / or method as private, protected and public, respectively. For package level access no modifies is used i.e. if we use no access modifier / specifier, it defaults to package level access. The following table summarizes different access specifiers / modifiers available in Java programming langauage:

private accessible only in this class
( no modifier ) accessible only in this package
protected accessible only in this package and in all subclasses of this class
public accessible everywhere this class is available

Similarly a class may be declared with the modifier public, in which case the class becomes visible to all classes, everywhere. On the contrary if a class has no modifier (the default, a.k.a. package-private) it becomes visible only within its own package.

For both fields and classes, package access is the default, and is used when no access modifier is specified. Java packages are discussed in the next lesson.

As discussed earlier, access control must be specified for every field and every method; there is no grouping as in C++. For example consider the following piece of code:

public
int x;
int y;


In the above piece of code only x is public; y gets the default, package access.

Static Fields and Methods
Fields and methods can also be declared static. If a field is declared as static, there is only one copy of the field for the entire class, rather than one copy for each instance of the class. A method that is declared as static cannot access any of the non-static fields of the class, and also it cannot call any non-static method. Methods that would be "free" functions in C++ i.e. not members of a class, should be static methods in Java. A public static field or method can be accessed from outside the class, with or without creating an instance of the class.

Final Fields and Methods
Fields and methods can also be declared final. A final method cannot be overridden in a subclass. A final field is like a constant: once it has been given a value, it cannot be assigned to again.
Next >>> Lesson No. 9: Java Packages







Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.