• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accessing instance variable

 
Swati Kadam
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Milton Ochoa
Ranch Hand
Posts: 336
Firefox Browser Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code has the same issue, but is simpler:



The second statement is not a valid statement.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic