Monday, July 26, 2021

Private in Java: Why should you always keep fields and methods private? Example

Making members private in Java is one of best coding practice. Private members (both fields and methods) are only accessible inside the class they are declared or inside inner classes. private keyword is one of four access modifier  provided by Java and its a most restrictive among all four e.g. public, default(package), protected and private. Though there is no access modifier called package, rather its a default access level provided by Java. In this Java tutorial we will see why should we always make members of class by default as private and answer to one of popular Java interview question can override private methods in Java.

This article is in continuation of my earlier post on Java e.g. 10 Object Oriented Design principles Java programmer should know and 10 best practice to follow while writing comments. If you haven’t read them already you may find them interesting and worth reading.


Why should you make your members private by default:

private keyword example, private variable, private method and class in javaAs I said earlier keeping member variable or method private as default provides Encapsulation. if you need it access from other class keep increasing accessibility step by step i.e. from private to default which is package-private i.e only accessible inside same package to protected  and finally public. Don't make any method by default public which most of Java programmers do, that's against concept of Encapsulation in Java. Here are some benefits of making variables or methods private in Java:



1) private methods are well encapsulated in class and developer knows that they are not used anywhere else in code which gives them confident to change, modify or enhance private method without any side-effect.

2) By looking to the private method you know by sure that no one is using it which is great help during debugging java program.

3) IDE like Netbeans and Eclipse use this information and automatically check whether private methods are used inside Class or not and can display relevant warning to improve code quality or delete unused statements, variables  or methods.

4) private methods use static binding in Java and they are bonded 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 optimize it.

5) Making variables private in java and providing getter and setter for them makes your class compatible Java bean naming convention and other reflection based frameworks like displaytag .


Can we override Private method in Java?

No you cannot override private methods in Java, private methods are non virtual and accessed differently than non-private methods. Since method overriding can only be done on Sub Class and since private method is not accessible in sub class or derived class, You just can not override them. Another possibility of overriding private methods in inner class by extending outer class, since private methods are accessible inside inner class. This will also not work because private methods are bonded during compile time and only Type (or Class) which is used to locate a private method. For example in below code where it looks like Inner SubClass is overriding private method , if you call privateMethod() with a type of Super Class but object of Sub Class, it will only execute privateMethod() declared in super Class.

Should I always make private method as final in Java

Using final and private in Java with method is a good choice but I don't think it offer any benefit in terms of performace or not. Rather this decision should be taken on the basis of design, functionality and ensuring readability of code. Since making a method final just limit there ability to be overridden, it doesn't make much sense to mark a private method as final in java, because private method can not overridden in Java by any means.


Important Points about private keyword in Java

Few important points to remember about private keyword in java before seeing example of private keyword and overriding private methods in Java which is not possible.

1.private keyword can be applied to fields, methods and inner class in Java.

2.Top level classes can not be private in Java.

3.Though private methods or variables are not accessible outside of Class, they can be accessed via reflection by using setAccessible(true) and changing there private visibility.

4.Private method can not be overridden in Java, not even inside inner classes.

5.private members allows Compiler and JVM to optimize it for better performance.

Example of private field and method in Java

Here is a code example or private keyword in Java. This examples shows that private methods uses static binding at compile time and can not be overridden. Don’t confuse with the output though regarding private variable because its accessible inside Inner classes. It will be compiler error if private variables used outside the class.

public class PrivateMemberExample {

    private String i_m_private = "I am private member, not accessible outside this Class";

    private void privateMethod() {
        System.out.println("Private method of Outer Class");
    }

    public static void main(String args[]) {
        PrivateMemberExample outerClass = new PrivateMemberExample();
        NestedClass nc = outerClass.new NestedClass();
        nc.showPrivate(); //shows that private method are accessible in inner class.
     
        outerClass = nc;
        nc.privateMethod(); //does not call private method from inner class because
                            // you can not override private method inside inner class.

    }

    class NestedClass extends PrivateMemberExample {

        public void showPrivate() {
            System.out.println("Accessing Private members of Outer class: " + i_m_private);
            privateMethod();
        }
     
        private void privateMethod() {
              System.out.println("Private method of Nested Class");
        }
    }
}


Output:
Accessing Private members of Outer class: I am private member, not accessible outside this Class
Private method of Outer Class
Private method of Outer Class




In Summary private keyword in java allows most restrictive access to variables and methods and offer strongest form of Encapsulation. private members are not accessible outside the class and private method can not be overridden.


Other Java Tutorials you may like

13 comments :

suraj said...

There is a question in one Java interview "Can we make class private in Java", I said no as class can only be public or without any modifier i.e. default access on package level, but he was keep asking. do you know when can we make class private in Java?

Jim said...

How to test private method in Java using JUnit, Since I can not call it outside the class It looks either I need to change access modifier form private to public or wrap it inside public method, let me know id you have better way of testing a private method in Unit or TestNG ?

Anonymous said...

Ques - Can we make class private in Java?
Ans - Yes! if it is an inner class.

Sandeep Kanabar said...

Hi Javin,

there is a typo in the code.
nc.privateMethod(); this should have been
outerClass.privateMethod();

And there is typo in the output too:
The 2nd line in output should be:
Private method of Nested Class

Correct me if I'm wrong.

Cheers,
Sandeep

Anonymous said...

Wrong wrong wrong. Only use private or final on classes that you know will never, ever, ever be maintained or used by someone else - which is to say "NEVER".

The language shouldn't even have private or final in it.

Anonymous said...

I executed above program:

code:

public class PrivateMemberExample {

private String i_m_private = "I am private member, not accessible outside this Class";

private void privateMethod() {
System.out.println("Private method of Outer Class");
}

public static void main(String args[]) {
PrivateMemberExample outerClass = new PrivateMemberExample();
NestedClass nc = outerClass.new NestedClass();
nc.showPrivate(); //shows that private method are accessible in inner class.

outerClass = nc;
nc.privateMethod(); //does not call private method from inner class because
// you can not override private method inside inner class.

}

class NestedClass extends PrivateMemberExample {

public void showPrivate() {
System.out.println("Accessing Private members of Outer class: " + i_m_private);
privateMethod();
}

private void privateMethod() {
System.out.println("Private method of Nested Class");
}
}
}


Output was:
Accessing Private members of Outer class: I am private member, not accessible outside this Class
Private method of Nested Class
Private method of Nested Class

JDK used: 1.7

May I know why is the output different from what is mentioned here.

Anonymous said...

Hey Javin..

When we run the above program on JDK 7,

Output was:
Accessing Private members of Outer class: I am private member, not accessible outside this Class
Private method of Nested Class
Private method of Nested Class

Can you please put some more light on it..

Anonymous said...

Is it the same if I have a public final without getter or is better set it as private and access with a getter method? Thanks.

Anonymous said...

Never use private, I know more about programming than the braindead morons that designed the Java language, and it completely breaks the OOP principles of inheritance and code reusability. Use package or protected instead.

Charles Roth said...

The one down-side of private methods is that you can't write unit-tests for them (or not without doing reflection and other unsavory practices! :-) )

I prefer package-protected, with a comment like "/*TestScope*/". It would be nice if we could have tested code and private methods, but Java doesn't allow that. In which case testing one's code IMHO trumps the privacy fetish.

Unknown said...

Good explanation Javin. Thank you for wonderful blog.

In above program output is wrong must be typo.

Actual output will be

Accessing Private members of Outer class: I am private member, not accessible outside this Class
Private method of Nested Class
Private method of Nested Class

Reason is Private methods are compile time binding. So in above program private methods are invoked using nc object which is of type NestedClass.

Just try to add outerClass.privateMethod(); after nc.privateMethod(); you can understand output better.

Accessing Private members of Outer class: I am private member, not accessible ou
tside this Class
Private method of Nested Class
Private method of Nested Class
Private method of Outer Class

Cheers!

attish raj said...

u can access through it caller

Unknown said...

Yes correct

Post a Comment