« back

Non Access Modifiers in Java

05 Mar 2013

In my last post Access Modifiers, we looked at encapsulation and some ways that this could be achieved, specifically while using java. Today, let's look at some java non access modifiers.

Non access modifiers can alter the behavior of elements in java. There are two levels on which this can occur, classes and members. On a class level, there are two non access modifiers to be aware of. Final and Abstract.

Final - When you declare a class final, this means that the class can not be subclassed. You would want to make a class final when you know that you do not want any of your methods to be overridden. If you take a look at some of the core classes in java, like Math for example, you will see that it is final to avoid people redefining how addition works for example.(Note the public access modifier since this should be available everywhere.)

1 public final class Math {
3 }

Abstract - Abstract classes are meant to be just that. They are not allowed to be instantiated, only subclassed. This can be useful when you want to ensure that certain functionality gets implemented into a class while still allowing the class to add it's own functionality.

1 abstract class Widget {
2     public abstract void methodToBeImplemented();
3 }

Methods can have their own non access modifiers as well. There are a lot of them but let's look at a few of them that are more commonly used.

Final - This is used as a preventive measure to not allow a method to be overwritten in a subclass.

1 public final void myMethod() {
2     do stuff;
3 }

Abstract - This example can be seen also above. A method is abstract when it is not actually implemented. This will force a subclass to provide implementation.

1 abstract class Widget {
2     public abstract void methodToBeImplemented();
3 }

Static - You use this when you want to want the method to belong to the class and not an instance of the class. Then when you want to call the method, you access it by calling ClassName.methodName without having an instance.

1     public static void myMethod() {
2         do something;
3     }

In addition to using these on modifiers on classes and methods, some of them can also be used on variables and they usually work along the same lines that they do for methods. A cool one to check out is calling final on an argument which will allow use of but not manipulation or assignment of within the scope of the method.

The more you know...

comments powered by Disqus