Search This Blog

Saturday, February 21, 2009

Basics of Instance and class variables with e.g

/*
# nstance methods can access instance variables and instance methods directly.
# Instance methods can access class variables and class methods directly.
# Class methods can access class variables and class methods directly.
# Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.
*/
/*
################################################
vik(), vik2(), x are static
vik1(), vik3(), y non-static
##################################################
*/
public class vars {
public static int x = 7; // class varibale
//public int y = 3;
private int y = 3; //instance variable

// a non-static can call only static not a non-static
// static fun can use only static varibales not non-static one
public static void vik() {
System.out.println("\n a static one \n"+ x);
vik2(); //static
//vik1(); non-static will give error
}

// a non-static can call both static or non-static fun and variables
public void vik1(){
System.out.println("\n not a static one \n " + x + y);
vik(); //static
vik3(); //non static
}

public static void vik2() {
System.out.println("\n a static one \n");
}

public void vik3(){
System.out.println("\n not a static one \n");
}


public static void main(String[] args) {
System.out.println(vars.x);
//System.out.println(vars.y);
//error non-static variable y cannot be referenced from a static context
//only static vars can use class name to access so called class variable

vars v = new vars();
System.out.println(v.y);
//vars.vik(); //or v.vik();
// vars.vik1();
//error non-static variable y cannot be referenced from a static context
v.vik1();
}
}

No comments:

Post a Comment