Declaring classes, variables, and methods
Now let's look at ways we can modify classes, methods, and variables. There are two kinds of modifiers -- access modifiers and non-access modifiers. The access modifiers allow us to restrict access or provide more access to our code.
Class modifiers
The access modifiers available are public, private, and protected. However, a top-level class can have only public and default access levels. If no access modifier is specified, the class will have default access. Only classes within the same package can see a class with default access. When a class is declared as public, all the classes from other packages can access it.
Let's see the effect of some non-access modifiers on classes. The final keyword does not allow the class to be extended. An abstract class cannot be instantiated, but can be extended by subclasses:
public final class Apple {..}
class GreenApple extends Apple {} // Not allowed, compile time error
Method and variable modifiers
All the access modifiers can be used for members of a class. The private members can only be accessed from inside the class. The protected members can only be accessed by classes in the same package or subclasses of the class. The public members can be accessed by any other class.
If there is no access modifier specified, these members will have default access and only other classes in the same package can access them.
Now let's explore other modifiers that can be applied to member declarations. Some of them can be applied only to methods while some can be applied only to variables, as illustrated in the figure below:
Modifiers for methods and variables
A synchronized method can be accessed by only one thread at a time. Transient variables cannot be serialized. An abstract method does not have an implementation; it has to be implemented by the first concrete subclass of the containing class. The class containing at least one abstract method has to be declared as abstract. However, an abstract class need not have any abstract methods in it:
public abstract class MyAbstractClass
{
public abstract void test();
}
The native modifier indicates that the method is not written in the Java language, but in a native language. The strictfp keyword , which is used only for methods and classes, forces floating points to adhere to IEE754 standard. A variable may be declared volatile, in which case a thread must reconcile its working copy of the field with the master copy every time it accesses the variable.
Static variables are shared by all instances of the class. Static methods and variables can be used without having any instances of that class at all:
class StaticTest
{
static int i = 0;
static void getVar()
{
i++;
System.out.println(i);
}
}
class Test
{
public static void main(String args[])
{
StaticTest.getVar();
}
}
1 comment: