Win a copy of Spring in Action (5th edition) this week in the Spring forum!
  • 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:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

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);


}
}
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!