Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in KB:page no 137 and 179

 
VIGNESHWAR VISWANATHAN
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic