Java Interview Reference Guide – Part 2
Join the DZone community and get the full member experience.
Join For FreeAccess Modifier
Please refer to Java Interview Reference Guide – Part 1 for basic OOPS concepts
Access modifier depicts how other classes access a class and its members (methods and variable.
The access modifiers are
- Private: A private variable or method (not external class) may only be used by an instance of the class that declares the variables or method.
- Default: A class’s data and method and class itself may be default. A class default features are accessible to any class in the same package.
- Protected: more accessible than default. Only variable and method may be declared as protected. A protected feature of a class is available to all subclasses of the class that owns the protected features. This access is provided even to subclasses that reside in a different package.
- Public: A public class, variable or method may be used access any Java program without any restriction
Note:
- The only access modifier permitted to non-inner class is public there is no such thing as protected or private top-level class.
- A feature may have at most one access modifier. If a feature has no access modifier then it access default mode.
- Method overridden privacy: Method may not be overridden to be more private.
The following table shows the access to members permitted by each modifier.
Apart from basic access modifier below table depicts modifiers in Java, which also use to alter the behavior of class and its members such as method, variable, inner classes.
Java Modifiers
Final
Final modifies may be applied to class, methods and variables and its mean that final features may not be changed. E.g.
- A final class may not be subclasses
- A final variable may not be modified once it has been assigned a value
- A final method may not be overridden
Note: If a final variable is a reference to an object, it is the reference that must stay the same, not the object.
Static:
The static modifier can be applied to variables, methods, code block and inner class. If Java instance variables are given separate memory for storage. If there is a need for a variable to be common to all the objects of a single java class, then the static modifier should be used in the variable declaration
- Static method: java static methods are common to classes and not tied to a java instance. Static method is not allowed to use non-static features of their class although they are free to access class’s static data and method. Static method may not be overridden to be non-static. Java static methods cannot use the ‘this’ keyword.
- Static block: A block of static code execute only exactly once while class loading.
- Static variables: Java instance variables are given separate memory for storage. If there is a need for a variable to be common to all the objects of a single java class, then the static modifier should be used in the variable declaration. Any java object that belongs to that class can modify its static variables. Also, an instance is not a must to modify the static variable and it can be accessed using the java class directly. Static variables can be accessed by java instance methods also. When the value of a constant is known at compile time it is declared ‘final’ using the ‘static’ keyword
- Static Inner class: Only an inner class can be declared using the static modifier and called nested static classes in java.
Outer and Inner classes (or Nested classes)
In Java not all classes have to be defined separate from each other. You can put the definition of one class inside the definition of another class. The inside class is called an inner class and the enclosing class is called an outer class. So when you define an inner class, it is a member of the outer class in much the same way as other members like attributes, methods and constructors.
When you access private data members of the outer class, the JDK compiler creates package-access member functions in the outer class for the inner class to access the private members. This leaves a security hole. In general we should avoid using inner classes.
Use inner class only when an inner class is only relevant in the context of the outer class and/or inner class can be made private so that only outer class can access it. Inner classes are used primarily to implement helper classes like Iterators, Comparators etc. that are used in the context of an outer class.
Difference between static and non-static nested classes
A non-static nested class (or ‘inner class’) has full access to the members of the class within which it is nested. A static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested.
In case of declaring member fields and methods, non-static inner class cannot have static fields and methods. But, in case of static inner class, can have static and non-static fields and method.
The instance of non-static inner class is created with the reference of object of outer class, in which it has defined; this means it has enclosing instance. But the instance of static inner class is created without the reference of Outer class, which means it does not have enclosing instance. E.g..
Public Class OuterClass { Class InnerClass { // static int x; not allowed here } Static class StaticInnerClass { Static int x; // allowed here } } Class Test { public static void main(String… str) { OuterClass oc=new OuterClass (); OuterClass.InnerClass obj1 =oc.new InnerClass();//need of inclosing instance OuterClass.StaticInnerClass obj2 =new OuterClass.SIC(); // no need of reference of object of outer class } }
Native
The native modifier can refer only to methods. Native indicate that body of a method is to be found outside of JVM.
Note: In the case of abstract methods, the body is in subclass with native method the body lies entirely outside Java virtual memory, in a library.
Transient
The transient modifier applies only to variable. A transient variables is not stored as part of its object’s persistent state. Use for security key, connection etc. that not required to searlized.
Synchronized
The synchronized modifier is used to control access to critical code in multi-threaded program. The synchronized keyword is one of the tools that make your code thread safe.
It is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads
When you mark a block of code as synchronized you use an object as a parameter. When an executing thread comes to such a block of code, it has to first wait until there is no other executing thread in a synchronized block on that same object. However a thread could enter the block of synchronized method other object.
But non-synchronized method in same object can access without checking lock.
If you synchronize on a static method you will synchronize on the class (object) and not on an instance (object). That means while execution of a static method the whole class is blocked. So other static synchronized methods are also blocke
When a thread has entered a synchronized instance method then no other thread can enter any of synchronized instance methods of the same instance
When a thread entered a synchronized static method then no other thread can enter any of synchronized static methods of the same class
Note: No link between synchronized static methods and synchronized non static methods, ie:if static synchronize and non-static synchronize method can run concurrently method unless your non-static method must explicitly synchronize on the class itself (ie, synchronized (MyClass.class) {…}
Volatile
Only variable may be volatile. Such variable might be modified asynchronously so the compiler takes special precaution The volatile modifier guarantees that any thread that reads a field will see the most recently written value
Use of volatile: One common example for using volatile is to use a volatile boolean variable as a flag to terminate a thread
Difference between Volatile and Synchronize:
So where volatile only synchronizes the value of one variable between thread memories and “main” memory, synchronized synchronizes the value of all variables between thread memory and “main” memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.
A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in “main” memory.
Effectively, a variable declared volatile must have it’s data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value.
Abstract
The abstract modifier can be applied to class and methods. A class that is abstract may not be instantiate and must be extends to assess. Abstract could not be applicable on class member variables
Example: Animal class has travel method and each subclass (snake, dog, bird) has its own way of travelling. So it is not possible to provide travel () in the superclass. Instead the Animal superclass declares travel () to be abstract.
Note:
- If a class contains one more abstract method, the compiler insists that the class must be declared abstract.
- Abstract is opposed to final. A final class may not be subclasses; an abstract class must be subclasses.
In design, you want the base class to present only an interface for its derived classes. This means, you don’t want anyone to actually instantiate an object of the base class. You only want to up cast to it (implicit up casting, which gives you polymorphic behavior), so that its interface can be used. This is accomplished by making that class abstract using the abstract keyword.
Provide some restriction on to not to instantiate the abstract class and whoever use should implement the abstract method. And provide polymorphism.
When to use an abstract class?
Abstract classes let you define some default behavior and force subclasses to provide any specific behavior.
For example: The Spring framework’s dependency injection promotes code to an interface principle abstract implementation in collection framework.
Published at DZone with permission of Nitin Kumar, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Exploratory Testing Tutorial: A Comprehensive Guide With Examples and Best Practices
-
How To Approach Java, Databases, and SQL [Video]
-
Effective Java Collection Framework: Best Practices and Tips
-
Revolutionizing Algorithmic Trading: The Power of Reinforcement Learning
Comments