• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

error in question number 208  RSS feed

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
208 in the Round-Up is as follows
can one object access a private variable of another object of the same class?
Answer given by the site is :
Yes.
Reason: Private means "private to the class" and not "private to the object"

According to me, the above answer is wrong. The access modifier 'private' means 'private to the object'.
 
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Private means --> private to the class!
If you get no or yes answers you only need to figure out 1 case where it is true and the answer is YES. The code below shows one true.

All instances (objects) will be able to change the PRIVATE class variable ... therefore in the above case the statement:
Can one object access a private variable of another object of the same class?
will be Yes!!
Regards,
Manfred.
 
Manjiri Purandare
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am answering my own question.
Try out this code, which shows that private data is "private to class" and not "private to object".
public class Test
{
private String privateStr;

public Test()
{
privateStr = "Original String";
}

public void method1()
{
Test object2 = new Test();
object2.privateStr = "New String";
// Note private data is accessed using dot operator
System.out.println("method1() prints : " + object2.privateStr);
}

public void method2(Test object3)
{
// Note private data is accessed using dot operator
System.out.println("method2() prints : " + object3.privateStr);
}

public static void main(String args[])
{
Test object1 = new Test();
object1.method1();

Test object3 = new Test();
object1.method2(object3);


}
}
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!