Skip to content

A word on access modifiers

September 6, 2011

Instance variables and methods will frequently find themselves prefferenced by a word  private, public, protected or friendly. In OO, there is the potential for lots of sharing of code.  This is a good thing because it reduces the amount of redundant code across various places.  The trade off is increased complexity in the form of access modifiers.

When you preference a variable or method with the keyword

  • keyword – availability to other classes
  • public – any class
  • protected – any class inheriting from that class
  • friendly – any class in the same package
  • private – only the defining class.

Most methods in classes are defined as public – this promotes code sharing and re-use, while most data members or instance variables are scoped as private.  When you are defining parent or super classes, it is common then to use protected, which allows classes inheriting to access.

Remember, these are instance variables that are used to control access to object state.

Class variables are handled via the static reserve word.  Static essentially means the variable is at the class level and will not change for each instance of an object of the class. By prefacing a variable declaration with the keyword static, you are saying that the identifiers following it are variables associated with the class, not each class instance object.

You wont find as many static method or variables in your classes.  Think of them as non changing for all the objects that come from the class.  Utility classes or classes that perform calculations and do not have state are often prefaced by the static keyword.  A static method can only access static variables not instance variables.

An example of referencing a static method Math.sin() would be

double value = Math.sin(someArg);

Note the method sin() is preferenced by package name Math but does NOT include an OBJECT reference.

The final keyword following the keyword static is used to represent a constant for the class. The following snippet

static final MAX_SPEED = 50;

means the variable MAX_SPEED is a constant for the entire class and will never change. statically defined variables are constants and should be represented in all uppercase letters.





From → Java

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: