permaculture playing cards*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Accessing instance variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Accessing instance variable" Watch "Accessing instance variable" New topic
Author

Accessing instance variable

Swati Kadam
Ranch Hand

Joined: Mar 05, 2008
Posts: 39
By commenting out which line will the following class compile with no errors ?

class ZZY {

transient final int i = 0;
transient final static int j = 10 ;
int k = 78 ;

char jack(){
return 'a';
}

public static void main ( String args [ ]) { // ---> 1
new ZZY ( ) . jack ( ) ; // ---> line 2
int d = new ZZY ( ) . j + new ZZY ( ) . i ; // ---> line 3
new ZZY ( ) . k ; // ---> line 4
System.out.println(newZZY().i+" "+new ZZY().j);//--> line 5
}
}


In this program you have to comment line 4...
new zzy().K; In this line new ZZY() returns object of class zzy and you can access any instance variable as object.varname...
but here why we cant access it?


SCJP / Preparing For SCWCD
Milton Ochoa
Ranch Hand

Joined: Oct 23, 2007
Posts: 336

Very intersting,

for me, called to the method or accesing directly to a instace variable, its the same.

i will take this on count.!
Tim Weide
Ranch Hand

Joined: Feb 19, 2008
Posts: 37
The following code has the same issue, but is simpler:



The second statement is not a valid statement.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Swati Kadam:
...you can access any instance variable as object.varname...
but here why we cant access it?

The reference is fine. The problem is that you're not doing anything with that line, so it's not a statement. If you use this reference in a complete statement, then it's fine. For example...

int x = new ZZY().k;

(This is the same answer I posted under your duplicate.)


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Accessing instance variable
 
Similar Threads
Doubt in Output of the following code
transient ????
interface to class assignment
Which method to call ?
Why this Output?