1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
/* Java static member variable example This Java Example shows how to declare and use static member variable inside a java class. */ public class StaticMemberExample { public static void main(String[] args) { ObjectCounter object1 = new ObjectCounter(); System.out.println(object1.getNumberOfObjects()); ObjectCounter object2 = new ObjectCounter(); System.out.println(object2.getNumberOfObjects()); } } class ObjectCounter{ /* * Static members are class level variables and shared by all the objects * of the class. * * To define static member, use static keyword * e.g. static int i=0; * * Please note that static member variables can be accessed inside * non static methods because they are class level variables. * */ static int counter=0; public ObjectCounter(){ /*increase the object counter. Since only one varible is shared between * all objects of this class, it always return number of objects till now. */ counter++; } //returns number of objects created till now public int getNumberOfObjects(){ return counter; } } |
Static Members cannot access in the non-static methods
Static Members can access in the static methods only
but u have written above as
#
*
#
* Static members are class level variables and shared by all the objects
#
* of the class.
Static memebers can be accessed from non-static methods,
But the reverse is not true.
i.e., static methods cannot access non-static members.
Compliler will give error like :”Non-static member is referenced from a static context”
Only static methods may access static members.
hence, change oublic int numberOfObjects() to public static int numberOfObjects()
You can also access static member from non static methods but it’s reverse not possible. so there is no need to change the code.
s what u said is correct
static member cannot accessed in non-static-method
given below is a program ive been trying to create,it has two static variables, and all the mathods are static and they dont have any return type.i’m enable to get the output of the prog.i need help please!
import java.util.Scanner;
class Mathop
{
static int a,b;
public static void getdata(int a,int b)
{
Mathop.a=a;
Mathop.b=b;
}
}
public class Maths
{
public static void ADD(int a,int b)
{
System.out.println(“sum = ” + (a+b));
}
public static void SUB(int a,int b)
{
System.out.println(“diff = ” + (a-b));
}
public static void MUL(int a,int b)
{
System.out.println(“mul = ” + (a*b));
}
public static void DIV(int a,int b)
{
System.out.println(“div = ” + (a/b));
}
public static void main(String[] args)
{
m.getdata(2,4);
ADD(a,b);
SUB(a,b);
MUL(a,b);
DIV(a,b);
}
}
public class Maths extends Mathop
or
Mathop.getdata(2,4);