File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in KB:page no 137 and 179 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 "Doubt in KB:page no 137 and 179" Watch "Doubt in KB:page no 137 and 179" New topic
Author

Doubt in KB:page no 137 and 179

VIGNESHWAR VISWANATHAN
Greenhorn

Joined: May 26, 2007
Posts: 17
In the chapter 2-Statics and method consider the code
class Foo {
int x = 3;
public static void main (String [] args) {
System.out.println("x is " + x);
} }

Here it gives a compiler error saying that the static method of a class cant access the non static(instance)variable. So far so good for me.

But in Chapter 3
public class BirthDate {
int year; // Instance variable
public static void main(String [] args) {
BirthDate bd = new BirthDate( );
bd.showYear();
}
public void showYear() {
System.out.println("The year is " + year);
}
}

When the program is started, it gives the variable year a value of zero, the default value for primitive number instance variables.
[i]If you consider the above example a static method cant access a non static(instance variables) or methods.But consider the above program.Here the output is fine.
Tell me the reasons.
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Originally posted by VIGNESHWAR VISWANATHAN:
In the chapter 2-Statics and method consider the code
class Foo {
int x = 3;
public static void main (String [] args) {
System.out.println("x is " + x);
} }

Here it gives a compiler error saying that the static method of a class cant access the non static(instance)variable. So far so good for me.

But in Chapter 3
public class BirthDate {
int year; // Instance variable
public static void main(String [] args) {
BirthDate bd = new BirthDate( );
bd.showYear();
}
public void showYear() {
System.out.println("The year is " + year);
}
}

When the program is started, it gives the variable year a value of zero, the default value for primitive number instance variables.
[i]If you consider the above example a static method cant access a non static(instance variables) or methods.But consider the above program.Here the output is fine.
Tell me the reasons.


In the second class, the instance variable year is being accessed from an instance method.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Doubt in KB:page no 137 and 179