Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Private instance variables accessed within the class

 
Arun Krishnan Nair
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the code given below, eventhough the variables i and sampleString is declared as private the same is accessable directly from the object through the main method of test class. Does it mean that private/protected declaration is ignored within the class?

public class Test {
private int i = 25;
private String sampleString = "Arun";
public static void main(String[] args) {
Test test = new Test();
System.out.println("String is --" + test.sampleString);
System.out.println("Int value is --" + test.i);
}
}
 
Ankit Garg
Sheriff
Posts: 9510
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes! Private members are accessible to the members of the class directly and through an object of the class...
 
ankit kumar
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can't access the private member outside the class anyhow directly.
 
sweety sinha
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes private member is accessible in the class
 
Arun Krishnan Nair
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes sweety..but it was a new knowledge for me that even if create object the private variables can be accessed using . operator

Thanks for all the replies
 
Siri Naray
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Private members of a class are accessible directly to all members of a class but from static members you cannot access directly but instead can access by creating an object.

eg
class Test
{

private int x;

void getX()
{
System.out.println(x};
}
public static void main(String[] args)
{
Test t;
System.out.println(t.x); //since main is a static method
}
}
[ September 03, 2008: Message edited by: Sirisha Ghatty ]
 
Ankit Garg
Sheriff
Posts: 9510
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sirisha Ghatty:

class Test
{
private int x;

public static void main(String[] args)
{
Test t;
System.out.println(Test.t); //since main is a static method
}
}


I think you were trying to write t.x instead of Test.t
 
Siri Naray
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yup its t.x
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic