/* * [TestPrivate.java] * * Summary: Explain how the private keyword is used. * * Copyright: (c) 2009-2017 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.8+ * * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/ * * Version History: * 1.0 2009-06-04 initial release. */ package com.mindprod.example; import static java.lang.System.*; /** * 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 final int pStatic = 2; /** * a private instance variable */ @SuppressWarnings( { "FieldMayBeStatic" } ) private final int pInstance = 3; /** * 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. } /** * 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. } /** * 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 an 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 an instance member from a static method // . You need an object. TestPrivate tp = new TestPrivate(); //noinspection AccessStaticViaInstance 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 //noinspection AccessStaticViaInstance 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 } }