Classes should always private in Java
Private keyword in java allows the most restrictive access to variables and methods. It offers the strongest form of Encapsulation.
Private members in java are not accessible outside the class and private methods can't be overridden.
Advantages of making variables or methods private in Java:
1) private methods are well wrapped inside the class and developer knows that they are not used anywhere else in code which gives them the confidence to change, modify or enhance private method without any side-effect.
2) Writing private method you know by sure that no one is using it, it helps in debugging more effectively.
3) private methods use compile-time binding in Java and they are evaluated during compile time which is fast compared to dynamic binding which occurs during runtime and also gives chance to JVM to either inline the method or optimizes it.
We can not declare the top-level class as private. Java allows only public and default modifiers for top-level classes in java.Inner classes can be private.
If we declare all classes private in java and want to run the application then we will get the runtime error.
Error - At least one public class is required in the main file.
Overriding private methods in Java
1). Overriding private methods in Java is invalid because a parent class's private methods are automatically final, and hidden from the derived class.
class Parent
{
private void display()
{
}
}
class Child extends Parent
{
//@Override its illegal //compile time error
private void display()
{
}
}
2). Allowing private methods to be overwritten will either cause a leak of encapsulation or a security risk.
Key points regarding private in Java
- Private keyword or modifier in java can be applied to member field, method, or nested class in Java.
- You can not use the private modifier on top-level class.
- private variables, methods, and classes are only accessible on the class on which they are declared.
- Private is the highest form of Encapsulation Java API provides and should be used as much as possible.
- It's best coding practice in Java to declare variable private by default.
- A private method can only be called from the class where it has declared.
- We can not declare an outer class as private. More precisely, we can not use the private access specifier with an outer class. As soon as you try to use the private access specifier with a class you will get a message in Eclipse as the error that only public, final, and abstract can be used as an access modifier with a class.
- Private classes are allowed, but only as inner or nested classes. If you have a private inner or nested class, then access is restricted to the scope of that outer class.
- If you have a private class on its own as a top-level class, then you can't get access to it from anywhere. So it does not make sense to have a top-level private class.
0 Comments
Post a Comment