Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is the program given wrong in K&B Book?

 
balajee annamalai
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Im preparing for SCJP1.4 and in Chapter 3 of Operators and assignments "From the classroom" section.They have given an example about shadowing of variables.



In the above example they are saying the output also but how will this code gets compiled beacuse size is an non static varaiable and we can't use that in the static main.
 
sridhar row
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you are right code wont compile. cant access non-static instance var from static main.
 
Bert Bates
author
Sheriff
Posts: 8898
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Balajee,

The error you're talking about is very, very, old. Do you have a hard copy of the book, or are you using a pdf that you borrowed from someone?

Thanks,

Bert
 
Carl Cordova
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe I am tired, but is size on line# 2 a Class variable and not an instance?
 
Kshitija Mitter
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The variable on line 2 in above cntext is Instance varibale

http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html

Hope this link will be useful.
[ May 28, 2008: Message edited by: Kshitija Mitter ]
 
Carl Cordova
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From page 207 of K&B, line 2?

class Foo {
static int size = 7;
static void changeIt(int size) {
size = size + 200;
System.out.println("size in changeIt is " + size);
}

public static void main (String [] args) {
Foo f = new Foo();
System.out.println("size = " + size);
changeIt(size);
System.out.println("size after changeIt is " + size);
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic