/* * @(#)TestPrivate.java * * Summary: Explain how the private keyword is used. * * Copyright: (c) 2009 Roedy Green, Canadian Mind Products, http://mindprod.com * * Licence: This software may be copied and used freely for any purpose but military. * http://mindprod.com/contact/nonmil.html * * Requires: JDK 1.6+ * * Created with: IntelliJ IDEA IDE. * * Version History: * 1.0 2009-06-04 - initial release. */ package com.mindprod.example; import static java.lang.System.out; /** * Explain how the private keyword is used. * * @author Roedy Green, Canadian Mind Products * @version 1.0 2009-06-04 - initial release. * @since 2009-06-04 */ final class TestPrivate { /** * a private static variable */ private static int pStatic = 2; // ------------------------------ FIELDS ------------------------------ /** * a private instance variable */ private int pInstance = 3; // -------------------------- STATIC METHODS -------------------------- /** * A private static method. * Get pStatic + 10 * * @return sum of pStatic + 10 */ private static int getBumped() { // can't access instance variables here without an object. return pStatic + 10; // ok to access private private static variables within private static method. } // -------------------------- OTHER METHODS -------------------------- /** * A private instance method. * Get sum of pInstance and pStatic. * * @return sum of pInstance and pStatic */ private int getSum() { return pInstance + pStatic; // ok to access private instance variable and private static variables within private instance method. } // --------------------------- main() method --------------------------- /** * Demonstratu use of priwate access from a static method * * @param args not used */ public static void main( String[] args ) { out.println( pStatic ); // 2 Ok to access private static member from static method // out.println( pInstance ); // SYNTAX EERROR. May not directly access a instance member from a static method. You need an object. out.println( getBumped() ); // 12 Ok to access private static method from static method of same class // out.println( getSum() ); // SYNTAX EERROR. May not directly access a instance member from a static method. You need an object. TestPrivate tp = new TestPrivate(); out.println( tp.pStatic ); // 2 Ok to access private static member from static method. This syntax not recommended. Use plain pStatic. out.println( tp.pInstance ); // 3 Ok to access private instance member from static method of same class out.println( tp.getBumped() ); // 12 Ok to access private static method from static method of same class. This syntax not recommended. Use plain getBumped(). out.println( tp.getSum() ); // 5 Ok to access private instance method from static method of same class } }