The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
May 2000

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

answer

Posted by quinith on May 02, 2001 at 4:46 PM

> >
> > In the following code, a private member function (getNumInstances) is being called by the class's
> > client. I thought private member functions are
> > only accessible to class's member functions and
> > not the external world. Please explain.

> >
> > public class CountInstances {
> > private static int numInstances = 0 ;
> >
> > private int getNumInstances() {
> > return numInstances;
> > }
> >
> > private static void addInstance() {
> > numInstances++;
> > }
> >
> > CountInstances() {
> > CountInstances.addInstance();
> > }
> >
> > public static void main(String args[]) {

> > CountInstances ref = new CountInstances();
> > System.out.println("Starting with " + ref.getNumInstances() + " Instances");
> >
> > }
> > }

> >

>
> private methods can be accessed only by the other methods of the
> same class. The object "ref" is a instance of CountInstances class
> so it has the access.

>

Ref may be, as it is in this case, an instance of the CountInstances class. However, this is not why it has access to the private method. It has access to the private method because it is being called within the class CountInstances (yes, that's right the method main is actually part of the CountInstances class.) Should a similiar instance (ref2) be created in a completely different class then then a call such as ref2.getNumInstances() would not be allowed.





Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us