• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Doubt in KB:page no 137 and 179

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic