• Post Reply Bookmark Topic Watch Topic
  • New Topic

Accessing default variable  RSS feed

 
MaheshS Kumbhar
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

How can we access default variable using object reference variable directly as in following code segment

class abc
{
int i;
public static void main(String[]s)
{
abc a = new abc();
System.out.print(a.i);
}
}
 
Juri Glass
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
MaheshS Kumbhar wrote:Hi

How can we access default variable using object reference variable directly as in following code segment

class abc
{
int i;
public static void main(String[]s)
{
abc a = new abc();
System.out.print(a.i);
}
}


This code compiles and gives you the value of i. Hints:
* Since you don't initialize your variable, it's autoinitialized to 0.
* You are using print. Try using println instead, it appends a newline. You then may see your output.

Best
Juri
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch

Please use the CODE button and maintain indentation; it makes your code easier to read.
 
MaheshS Kumbhar
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jury for replying to my post but actually I was expecting somewhat different answer. What I know as of now is that we can access only public variables directly using object reference variable and no need to access them via member methods.

But here in this case, we are actually accessing default variable using reference variable as it is public variable.

Is it valid scenario to access default variable using object reference variable?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A member variable with default access (i.e. not public, private or protected) can be accessed from inside the class, and from all classes in the same package. See Controlling Access to Members of a Class in Sun's Java Tutorials.

The main() method is in the same class abc as the member variable i, so main() can access i in an abc object.
 
Vinod Tiwari
Ranch Hand
Posts: 466
1
IntelliJ IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please go through access control

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