Related
To be specific, I was trying this code:
package hello;
public class Hello {
Clock clock = new Clock();
public static void main(String args[]) {
clock.sayTime();
}
}
But it gave the error
Cannot access non-static field in static method main
So I changed the declaration of clock to this:
static Clock clock = new Clock();
And it worked. What does it mean to put that keyword before the declaration? What exactly will it do and/or restrict in terms of what can be done to that object?
static members belong to the class instead of a specific instance.
It means that only one instance of a static field exists[1] even if you create a million instances of the class or you don't create any. It will be shared by all instances.
Since static methods also do not belong to a specific instance, they can't refer to instance members. In the example given, main does not know which instance of the Hello class (and therefore which instance of the Clock class) it should refer to. static members can only refer to static members. Instance members can, of course access static members.
Side note: Of course, static members can access instance members through an object reference.
Example:
public class Example {
private static boolean staticField;
private boolean instanceField;
public static void main(String[] args) {
// a static method can access static fields
staticField = true;
// a static method can access instance fields through an object reference
Example instance = new Example();
instance.instanceField = true;
}
[1]: Depending on the runtime characteristics, it can be one per ClassLoader or AppDomain or thread, but that is beside the point.
It means that there is only one instance of "clock" in Hello, not one per each separate instance of the "Hello" class, or more-so, it means that there will be one commonly shared "clock" reference among all instances of the "Hello" class.
So if you were to do a "new Hello" anywhere in your code:
A- in the first scenario (before the change, without using "static"), it would make a new clock every time a "new Hello" is called, but
B- in the second scenario (after the change, using "static"), every "new Hello" instance would still share and use the initial and same "clock" reference first created.
Unless you needed "clock" somewhere outside of main, this would work just as well:
package hello;
public class Hello
{
public static void main(String args[])
{
Clock clock=new Clock();
clock.sayTime();
}
}
The static keyword means that something (a field, method or nested class) is related to the type rather than any particular instance of the type. So for example, one calls Math.sin(...) without any instance of the Math class, and indeed you can't create an instance of the Math class.
For more information, see the relevant bit of Oracle's Java Tutorial.
Sidenote
Java unfortunately allows you to access static members as if they were instance members, e.g.
// Bad code!
Thread.currentThread().sleep(5000);
someOtherThread.sleep(5000);
That makes it look as if sleep is an instance method, but it's actually a static method - it always makes the current thread sleep. It's better practice to make this clear in the calling code:
// Clearer
Thread.sleep(5000);
The static keyword in Java means that the variable or function is shared between all instances of that class as it belongs to the type, not the actual objects themselves.
So if you have a variable: private static int i = 0; and you increment it (i++) in one instance, the change will be reflected in all instances. i will now be 1 in all instances.
Static methods can be used without instantiating an object.
Basic usage of static members...
public class Hello
{
// value / method
public static String staticValue;
public String nonStaticValue;
}
class A
{
Hello hello = new Hello();
hello.staticValue = "abc";
hello.nonStaticValue = "xyz";
}
class B
{
Hello hello2 = new Hello(); // here staticValue = "abc"
hello2.staticValue; // will have value of "abc"
hello2.nonStaticValue; // will have value of null
}
That's how you can have values shared in all class members without sending class instance Hello to other class. And whit static you don't need to create class instance.
Hello hello = new Hello();
hello.staticValue = "abc";
You can just call static values or methods by class name:
Hello.staticValue = "abc";
Static means that you don't have to create an instance of the class to use the methods or variables associated with the class. In your example, you could call:
Hello.main(new String[]()) //main(...) is declared as a static function in the Hello class
directly, instead of:
Hello h = new Hello();
h.main(new String[]()); //main(...) is a non-static function linked with the "h" variable
From inside a static method (which belongs to a class) you cannot access any members which are not static, since their values depend on your instantiation of the class. A non-static Clock object, which is an instance member, would have a different value/reference for each instance of your Hello class, and therefore you could not access it from the static portion of the class.
Static in Java:
Static is a Non Access Modifier.
The static keyword belongs to the class than instance of the class.
can be used to attach a Variable or Method to a Class.
Static keyword CAN be used with:
Method
Variable
Class nested within another Class
Initialization Block
CAN'T be used with:
Class (Not Nested)
Constructor
Interfaces
Method Local Inner Class(Difference then nested class)
Inner Class methods
Instance Variables
Local Variables
Example:
Imagine the following example which has an instance variable named count which in incremented in the constructor:
package pkg;
class StaticExample {
int count = 0;// will get memory when instance is created
StaticExample() {
count++;
System.out.println(count);
}
public static void main(String args[]) {
StaticExample c1 = new StaticExample();
StaticExample c2 = new StaticExample();
StaticExample c3 = new StaticExample();
}
}
Output:
1 1 1
Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won't reflect to other objects.
Now if we change the instance variable count to a static one then the program will produce different output:
package pkg;
class StaticExample {
static int count = 0;// will get memory when instance is created
StaticExample() {
count++;
System.out.println(count);
}
public static void main(String args[]) {
StaticExample c1 = new StaticExample();
StaticExample c2 = new StaticExample();
StaticExample c3 = new StaticExample();
}
}
Output:
1 2 3
In this case static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.
Static with Final:
The global variable which is declared as final and static remains unchanged for the whole execution. Because, Static members are stored in the class memory and they are loaded only once in the whole execution. They are common to all objects of the class. If you declare static variables as final, any of the objects can’t change their value as it is final. Therefore, variables declared as final and static are sometimes referred to as Constants. All fields of interfaces are referred as constants, because they are final and static by default.
Picture Resource : Final Static
To add to existing answers, let me try with a picture:
An interest rate of 2% is applied to ALL savings accounts. Hence it is static.
A balance should be individual, so it is not static.
This discussion has so far ignored classloader considerations. Strictly speaking, Java static fields are shared between all instances of a class for a given classloader.
A field can be assigned to either the class or an instance of a class. By default fields are instance variables. By using static the field becomes a class variable, thus there is one and only one clock. If you make a changes in one place, it's visible everywhere. Instance varables are changed independently of one another.
In Java, the static keyword can be simply regarded as indicating the following:
"without regard or relationship to any particular instance"
If you think of static in this way, it becomes easier to understand its use in the various contexts in which it is encountered:
A static field is a field that belongs to the class rather than to any particular instance
A static method is a method that has no notion of this; it is defined on the class and doesn't know about any particular instance of that class unless a reference is passed to it
A static member class is a nested class without any notion or knowledge of an instance of its enclosing class (unless a reference to an enclosing class instance is passed to it)
The keyword static is used to denote a field or a method as belonging to the class itself and not to any particular instance. Using your code, if the object Clock is static, all of the instances of the Hello class will share this Clock data member (field) in common. If you make it non-static, each individual instance of Hello will have a unique Clock.
You added a main method to your class Hello so that you could run the code. The problem with that is that the main method is static and as such, it cannot refer to non-static fields or methods inside of it. You can resolve this in two ways:
Make all fields and methods of the Hello class static so that they could be referred to inside the main method. This is not a good thing to do (or the wrong reason to make a field and/or a method static)
Create an instance of your Hello class inside the main method and access all its fields and methods the way they were intended to be accessed and used in the first place.
For you, this means the following change to your code:
package hello;
public class Hello {
private Clock clock = new Clock();
public Clock getClock() {
return clock;
}
public static void main(String args[]) {
Hello hello = new Hello();
hello.getClock().sayTime();
}
}
static methods don't use any instance variables of the class they are defined in. A very good explanation of the difference can be found on this page
I have developed a liking for static methods (only, if possible) in "helper" classes.
The calling class need not create another member (instance) variable of the helper class. You just call the methods of the helper class. Also the helper class is improved because you no longer need a constructor, and you need no member (instance) variables.
There are probably other advantages.
Static makes the clock member a class member instead of an instance member. Without the static keyword you would need to create an instance of the Hello class (which has a clock member variable) - e.g.
Hello hello = new Hello();
hello.clock.sayTime();
//Here is an example
public class StaticClass
{
static int version;
public void printVersion() {
System.out.println(version);
}
}
public class MainClass
{
public static void main(String args[]) {
StaticClass staticVar1 = new StaticClass();
staticVar1.version = 10;
staticVar1.printVersion() // Output 10
StaticClass staticVar2 = new StaticClass();
staticVar2.printVersion() // Output 10
staticVar2.version = 20;
staticVar2.printVersion() // Output 20
staticVar1.printVersion() // Output 20
}
}
Can also think of static members not having a "this" pointer. They are shared among all instances.
Understanding Static concepts
public class StaticPractise1 {
public static void main(String[] args) {
StaticPractise2 staticPractise2 = new StaticPractise2();
staticPractise2.printUddhav(); //true
StaticPractise2.printUddhav(); /* false, because printUddhav() is although inside StaticPractise2, but it is where exactly depends on PC program counter on runtime. */
StaticPractise2.printUddhavsStatic1(); //true
staticPractise2.printUddhavsStatic1(); /*false, because, when staticPractise2 is blueprinted, it tracks everything other than static things and it organizes in its own heap. So, class static methods, object can't reference */
}
}
Second Class
public class StaticPractise2 {
public static void printUddhavsStatic1() {
System.out.println("Uddhav");
}
public void printUddhav() {
System.out.println("Uddhav");
}
}
main() is a static method which has two fundamental restrictions:
The static method cannot use a non-static data member or directly call non-static method.
this() and super() cannot be used in static context.
class A {
int a = 40; //non static
public static void main(String args[]) {
System.out.println(a);
}
}
Output: Compile Time Error
A question was asked here about the choice of the word 'static' for this concept. It was dup'd to this question, but I don't think the etymology has been clearly addressed. So...
It's due to keyword reuse, starting with C.
Consider data declarations in C (inside a function body):
void f() {
int foo = 1;
static int bar = 2;
:
}
The variable foo is created on the stack when the function is entered (and destroyed when the function terminates). By contrast, bar is always there, so it's 'static' in the sense of common English - it's not going anywhere.
Java, and similar languages, have the same concept for data. Data can either be allocated per instance of the class (per object) or once for the entire class. Since Java aims to have familiar syntax for C/C++ programmers, the 'static' keyword is appropriate here.
class C {
int foo = 1;
static int bar = 2;
:
}
Lastly, we come to methods.
class C {
int foo() { ... }
static int bar() { ... }
:
}
There is, conceptually speaking, an instance of foo() for every instance of class C. There is only one instance of bar() for the entire class C. This is parallel to the case we discussed for data, and therefore using 'static' is again a sensible choice, especially if you don't want to add more reserved keywords to your language.
Static Variables Can only be accessed only in static methods, so when we declare the static variables those getter and setter methods will be static methods
static methods is a class level we can access using class name
The following is example for Static Variables Getters And Setters:
public class Static
{
private static String owner;
private static int rent;
private String car;
public String getCar() {
return car;
}
public void setCar(String car) {
this.car = car;
}
public static int getRent() {
return rent;
}
public static void setRent(int rent) {
Static.rent = rent;
}
public static String getOwner() {
return owner;
}
public static void setOwner(String owner) {
Static.owner = owner;
}
}
A member in a Java program can be declared as static using the keyword “static” preceding its declaration/definition. When a member is declared static, then it essentially means that the member is shared by all the instances of a class without making copies of per instance.
Thus static is a non-class modifier used in Java and can be applied to the following members:
Variables
Methods
Blocks
Classes (more specifically, nested classes)
When a member is declared static, then it can be accessed without using an object. This means that before a class is instantiated, the static member is active and accessible. Unlike other non-static class members that cease to exist when the object of the class goes out of scope, the static member is still obviously active.
Static Variable in Java
A member variable of a class that is declared as static is called the Static Variable. It is also called as the “Class variable”. Once the variable is declared as static, memory is allocated only once and not every time when a class is instantiated. Hence you can access the static variable without a reference to an object.
The following Java program depicts the usage of Static variables:
class Main
{
// static variables a and b
static int a = 10;
static int b;
static void printStatic()
{
a = a /2;
b = a;
System.out.println("printStatic::Value of a : "+a + " Value of b :
"+b);
}
public static void main(String[] args)
{
printStatic();
b = a*5;
a++;
System.out.println("main::Value of a : "+a + " Value of b : "+b);
}
}
output::
printStatic::Value of a : Value of b : 5
main::Value of a : 6 Value of b : 25
In the above program, we have two static variables i.e. a and b. We modify these variables in a function “printStatic” as well as in “main”. Note that the values of these static variables are preserved across the functions even when the scope of the function ends. The output shows the values of variables in two functions.
Static Method
A method in Java is static when it is preceded by the keyword “static”.
Some points that you need to remember about the static method include:
A static method belongs to the class as against other non-static
methods that are invoked using the instance of a class.
To invoke a static method, you don’t need a class object.
The static data members of the class are accessible to the static
method. The static method can even change the values of the static
data member.
A static method cannot have a reference to ‘this’ or ‘super’ members.
Even if a static method tries to refer them, it will be a compiler
error.
Just like static data, the static method can also call other static
methods. A static method cannot refer to non-static data members or
variables and cannot call non-static methods too.
The following program shows the implementation of the static method in Java:
class Main
{
// static method
static void static_method()
{
System.out.println("Static method in Java...called without any
object");
}
public static void main(String[] args)
{
static_method();
}
}
output:
Static method in Java...called without any object
Static Block In Java
Just as you have function blocks in programming languages like C++, C#, etc. in Java also, there is a special block called “static” block that usually includes a block of code related to static data.
This static block is executed at the moment when the first object of the class is created (precisely at the time of classloading) or when the static member inside the block is used.
The following program shows the usage of a static block.
class Main
{
static int sum = 0;
static int val1 = 5;
static int val2;
// static block
static {
sum = val1 + val2;
System.out.println("In static block, val1: " + val1 + " val2: "+
val2 + " sum:" + sum);
val2 = val1 * 3;
sum = val1 + val2;
}
public static void main(String[] args)
{
System.out.println("In main function, val1: " + val1 + " val2: "+ val2 + " sum:" + sum);
}
}
output:
In static block, val1: 5 val2: 0 sum:5
In main function, val1: val2: 15 sum:20
Static Class
In Java, you have static blocks, static methods, and even static variables. Hence it’s obvious that you can also have static classes. In Java, it is possible to have a class inside another class and this is called a Nested class. The class that encloses the nested class is called the Outer class.
In Java, although you can declare a nested class as Static it is not possible to have the outer class as Static.
Let’s now explore the static nested classes in Java.
Static Nested Class
As already mentioned, you can have a nested class in Java declared as static. The static nested class differs from the non-static nested class(inner class) in certain aspects as listed below.
Unlike the non-static nested class, the nested static class doesn’t need an outer class reference.
A static nested class can access only static members of the outer class as against the non-static classes that can access static as well as non-static members of the outer class.
An example of a static nested class is given below.
class Main{
private static String str = "SoftwareTestingHelp";
//Static nested class
static class NestedClass{
//non-static method
public void display() {
System.out.println("Static string in OuterClass: " + str);
}
}
public static void main(String args[])
{
Main.NestedClassobj = new Main.NestedClass();
obj.display();
}
}
output
Static string in OuterClass: SoftwareTestingHelp
I think this is how static keyword works in java.
I've written this test code:
class MyProgram
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
But it gives the following error:
Main.java:6: error: non-static variable count cannot be referenced from a static context
System.out.println(count);
^
How do I get my methods to recognize my class variables?
You must understand the difference between a class and an instance of that class. If you see a car on the street, you know immediately that it's a car even if you can't see which model or type. This is because you compare what you see with the class "car". The class contains which is similar to all cars. Think of it as a template or an idea.
At the same time, the car you see is an instance of the class "car" since it has all the properties which you expect: There is someone driving it, it has an engine, wheels.
So the class says "all cars have a color" and the instance says "this specific car is red".
In the OO world, you define the class and inside the class, you define a field of type Color. When the class is instantiated (when you create a specific instance), memory is reserved for the color and you can give this specific instance a color. Since these attributes are specific, they are non-static.
Static fields and methods are shared with all instances. They are for values which are specific to the class and not a specific instance. For methods, this usually are global helper methods (like Integer.parseInt()). For fields, it's usually constants (like car types, i.e. something where you have a limited set which doesn't change often).
To solve your problem, you need to instantiate an instance (create an object) of your class so the runtime can reserve memory for the instance (otherwise, different instances would overwrite each other which you don't want).
In your case, try this code as a starting block:
public static void main (String[] args)
{
try
{
MyProgram7 obj = new MyProgram7 ();
obj.run (args);
}
catch (Exception e)
{
e.printStackTrace ();
}
}
// instance variables here
public void run (String[] args) throws Exception
{
// put your code here
}
The new main() method creates an instance of the class it contains (sounds strange but since main() is created with the class instead of with the instance, it can do this) and then calls an instance method (run()).
Static fields and methods are connected to the class itself and not to its instances. If you have a class A, a 'normal' (usually called instance) method b, and a static method c, and you make an instance a of your class A, the calls to A.c() and a.b() are valid. Method c() has no idea which instance is connected, so it cannot use non-static fields.
The solution for you is that you either make your fields static or your methods non-static. Your main could look like this then:
class Programm {
public static void main(String[] args) {
Programm programm = new Programm();
programm.start();
}
public void start() {
// can now access non-static fields
}
}
The static keyword modifies the lifecycle of a method or variable within a class. A static method or variable is created at the time a class is loaded. A method or variable that is not declared as static is created only when the class is instantiated as an object for example by using the new operator.
The lifecycle of a class, in broad terms, is:
the source code for the class is written creating a template or
pattern or stamp which can then be used to
create an object with the new operator using the class to make an instance of the class as an actual object and then when done with the object
destroy the object reclaiming the resources it is holding such as memory during garbage collection.
In order to have an initial entry point for an application, Java has adopted the convention that the Java program must have a class that contains a method with an agreed upon or special name. This special method is called main(). Since the method must exist whether the class containing the main method has been instantiated or not, the main() method must be declared with the static modifier so that as soon as the class is loaded, the main() method is available.
The result is that when you start your Java application by a command line such as java helloworld a series of actions happen. First of all a Java Virtual Machine is started up and initialized. Next the helloworld.class file containing the compiled Java code is loaded into the Java Virtual Machine. Then the Java Virtual Machine looks for a method in the helloworld class that is called main(String [] args). this method must be static so that it will exist even though the class has not actually been instantiated as an object. The Java Virtual Machine does not create an instance of the class by creating an object from the class. It just loads the class and starts execution at the main() method.
So you need to create an instance of your class as an object and then you can access the methods and variables of the class that have not been declared with the static modifier. Once your Java program has started with the main() function you can then use any variables or methods that have the modifier of static since they exist as part of the class being loaded.
However, those variables and methods of the class which are outside of the main() method which do not have the static modifier can not be used until an instance of the class has been created as an object within the main() method. After creating the object you can then use the variables and methods of the object. An attempt to use the variables and methods of the class which do not have the static modifier without going through an object of the class is caught by the Java compiler at compile time and flagged as an error.
import java.io.*;
class HelloWorld {
int myInt; // this is a class variable that is unique to each object
static int myInt2; // this is a class variable shared by all objects of this class
static void main (String [] args) {
// this is the main entry point for this Java application
System.out.println ("Hello, World\n");
myInt2 = 14; // able to access the static int
HelloWorld myWorld = new HelloWorld();
myWorld.myInt = 32; // able to access non-static through an object
}
}
To be able to access them from your static methods they need to be static member variables, like this:
public class MyProgram7 {
static Scanner scan = new Scanner(System.in);
static int compareCount = 0;
static int low = 0;
static int high = 0;
static int mid = 0;
static int key = 0;
static Scanner temp;
static int[]list;
static String menu, outputString;
static int option = 1;
static boolean found = false;
public static void main (String[]args) throws IOException {
...
Let's analyze your program first..
In your program, your first method is main(), and keep it in mind it is the static method... Then you declare the local variable for that method (compareCount, low, high, etc..). The scope of this variable is only the declared method, regardless of it being a static or non static method. So you can't use those variables outside that method. This is the basic error u made.
Then we come to next point. You told static is killing you. (It may be killing you but it only gives life to your program!!) First you must understand the basic thing.
*Static method calls only the static method and use only the static variable.
*Static variable or static method are not dependent on any instance of that class. (i.e. If you change any state of the static variable it will reflect in all objects of the class)
*Because of this you call it as a class variable or a class method.
And a lot more is there about the "static" keyword.
I hope now you get the idea. First change the scope of the variable and declare it as a static (to be able to use it in static methods).
And the advice for you is: you misunderstood the idea of the scope of the variables and static functionalities. Get clear idea about that.
The very basic thing is static variables or static methods are at class level. Class level variables or methods gets loaded prior to instance level methods or variables.And obviously the thing which is not loaded can not be used. So java compiler not letting the things to be handled at run time resolves at compile time. That's why it is giving you error non-static things can not be referred from static context. You just need to read about Class Level Scope, Instance Level Scope and Local Scope.
Now you can add/use instances with in the method
public class Myprogram7 {
Scanner scan;
int compareCount = 0;
int low = 0;
int high = 0;
int mid = 0;
int key = 0;
Scanner temp;
int[]list;
String menu, outputString;
int option = 1;
boolean found = false;
private void readLine() {
}
private void findkey() {
}
private void printCount() {
}
public static void main(String[] args){
Myprogram7 myprg=new Myprogram7();
myprg.readLine();
myprg.findkey();
myprg.printCount();
}
}
I will try to explain the static thing to you. First of all static variables do not belong to any particular instance of the class. They are recognized with the name of the class. Static methods again do not belong again to any particular instance. They can access only static variables. Imagine you call MyClass.myMethod() and myMethod is a static method. If you use non-static variables inside the method, how the hell on earth would it know which variables to use? That's why you can use from static methods only static variables. I repeat again they do NOT belong to any particular instance.
The first thing is to know the difference between an instance of a class, and the class itself. A class models certain properties, and the behaviour of the whole in the context of those properties. An instance will define specific values for those properties.
Anything bound to the static keyword is available in the context of the class rather than in the context of an instance of the class
As a corollary to the above
variables within a method can not be static
static fields, and methods must be invoked using the class-name e.g. MyProgram7.main(...)
The lifetime of a static field/method is equivalent to the lifetime of your application
E.g.
Say, car has the property colour, and exhibits the behaviour 'motion'.
An instance of the car would be a Red Volkswagen Beetle in motion at 25kmph.
Now a static property of the car would be the number of wheels (4) on the road, and this would apply to all cars.
HTH
Before you call an instance method or instance variable It needs a object(Instance). When instance variable is called from static method compiler doesn't know which is the object this variable belongs to. Because static methods doesn't have an object (Only one copy always). When you call an instance variable or instance methods from instance method it refer the this object. It means the variable belongs to whatever object created and each object have it's own copy of instance methods and variables.
Static variables are marked as static and instance variables doesn't have specific keyword.
It is ClassLoader responsible to load the class files.Let's see what happens when we write our own classes.
Example 1:
class StaticTest {
static int a;
int b;
int c;
}
Now we can see that class "StaticTest" has 3 fields.But actually there is no existence of b,c member variable.But why ???. OK Lest's see. Here b,c are instance variable.Since instance variable gets the memory at the time of object creation. So here b,c are not getting any memory yet. That's why there is no existence of b,c. So There is only existence of a.
For ClassLoader it has only one information about a. ClassLoader yet not recognize b,c because it's object not instantiated yet.
Let's see another example:
Example 2:
class StaticTest {
public void display() {
System.out.println("Static Test");
}
public static void main(String []cmd) {
display();
}
}
Now if we try to compile this code compiler will give CE error.
CE: non-static method display() cannot be referenced from a static context.
Now For ClassLoader it looks like:
class StaticTest {
public static void main(String []cmd) {
display();
}
}
In Example 2 CE error is because we call non static method from a static context. So it is not possible for ClassLoader to recognize method display() at compile time.So compile time error is occurred.
This is bit diff to explain about static key word for all beginners.
You wil get to know it clearly when you work more with Classes and Objects.
|*| Static : Static items can be called with Class Name
If you observe in codes, Some functions are directly called with Class names like
NamCls.NamFnc();
System.out.println();
This is because NamFnc and println wil be declared using key word static before them.
|*| Non Static :Non Static items can be called with Class Variable
If its not static, you need a variable of the class,
put dot after the class variable and
then call function.
NamCls NamObjVar = new NamCls();
NamObjVar.NamFnc();
Below code explains you neatly
|*| Static and non Static function in class :
public class NamCls
{
public static void main(String[] args)
{
PlsPrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamObjVar.PrnFnc("Tst Txt");
}
static void PlsPrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
|*| Static and non Static Class inside a Class :
public class NamCls
{
public static void main(String[] args)
{
NamTicCls NamTicVaj = new NamTicCls();
NamTicVaj.PrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamNicCls NamNicVar = NamObjVar.new NamNicCls();
NamNicVar.PrnFnc("Tst Txt");
}
static class NamTicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
class NamNicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
}
In the Java programming language, the keyword static indicates that the particular member belongs to a type itself, rather than to an instance of that type.
This means that only one instance of that static member is created which is shared across all instances of the class.
So if you want to use your int count = 0; in static void main() , count variable must be declared as static
static int count = 0;
In this Program you want to use count, so declare count method as a static
class MyProgram<br>
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
Hear you can declare this method as a public private and protected also. If you are using this method you can create a secure application.
class MyProgram
{
static int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
This is because you do not create instance of the model class, you have to create instances every time you use non-static methods or variables.
you can easily fix this see below images
without making instance of class
My model class file
By just creating instance then use class non-static methods or variables easily error gone
I've written this test code:
class MyProgram
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
But it gives the following error:
Main.java:6: error: non-static variable count cannot be referenced from a static context
System.out.println(count);
^
How do I get my methods to recognize my class variables?
You must understand the difference between a class and an instance of that class. If you see a car on the street, you know immediately that it's a car even if you can't see which model or type. This is because you compare what you see with the class "car". The class contains which is similar to all cars. Think of it as a template or an idea.
At the same time, the car you see is an instance of the class "car" since it has all the properties which you expect: There is someone driving it, it has an engine, wheels.
So the class says "all cars have a color" and the instance says "this specific car is red".
In the OO world, you define the class and inside the class, you define a field of type Color. When the class is instantiated (when you create a specific instance), memory is reserved for the color and you can give this specific instance a color. Since these attributes are specific, they are non-static.
Static fields and methods are shared with all instances. They are for values which are specific to the class and not a specific instance. For methods, this usually are global helper methods (like Integer.parseInt()). For fields, it's usually constants (like car types, i.e. something where you have a limited set which doesn't change often).
To solve your problem, you need to instantiate an instance (create an object) of your class so the runtime can reserve memory for the instance (otherwise, different instances would overwrite each other which you don't want).
In your case, try this code as a starting block:
public static void main (String[] args)
{
try
{
MyProgram7 obj = new MyProgram7 ();
obj.run (args);
}
catch (Exception e)
{
e.printStackTrace ();
}
}
// instance variables here
public void run (String[] args) throws Exception
{
// put your code here
}
The new main() method creates an instance of the class it contains (sounds strange but since main() is created with the class instead of with the instance, it can do this) and then calls an instance method (run()).
Static fields and methods are connected to the class itself and not to its instances. If you have a class A, a 'normal' (usually called instance) method b, and a static method c, and you make an instance a of your class A, the calls to A.c() and a.b() are valid. Method c() has no idea which instance is connected, so it cannot use non-static fields.
The solution for you is that you either make your fields static or your methods non-static. Your main could look like this then:
class Programm {
public static void main(String[] args) {
Programm programm = new Programm();
programm.start();
}
public void start() {
// can now access non-static fields
}
}
The static keyword modifies the lifecycle of a method or variable within a class. A static method or variable is created at the time a class is loaded. A method or variable that is not declared as static is created only when the class is instantiated as an object for example by using the new operator.
The lifecycle of a class, in broad terms, is:
the source code for the class is written creating a template or
pattern or stamp which can then be used to
create an object with the new operator using the class to make an instance of the class as an actual object and then when done with the object
destroy the object reclaiming the resources it is holding such as memory during garbage collection.
In order to have an initial entry point for an application, Java has adopted the convention that the Java program must have a class that contains a method with an agreed upon or special name. This special method is called main(). Since the method must exist whether the class containing the main method has been instantiated or not, the main() method must be declared with the static modifier so that as soon as the class is loaded, the main() method is available.
The result is that when you start your Java application by a command line such as java helloworld a series of actions happen. First of all a Java Virtual Machine is started up and initialized. Next the helloworld.class file containing the compiled Java code is loaded into the Java Virtual Machine. Then the Java Virtual Machine looks for a method in the helloworld class that is called main(String [] args). this method must be static so that it will exist even though the class has not actually been instantiated as an object. The Java Virtual Machine does not create an instance of the class by creating an object from the class. It just loads the class and starts execution at the main() method.
So you need to create an instance of your class as an object and then you can access the methods and variables of the class that have not been declared with the static modifier. Once your Java program has started with the main() function you can then use any variables or methods that have the modifier of static since they exist as part of the class being loaded.
However, those variables and methods of the class which are outside of the main() method which do not have the static modifier can not be used until an instance of the class has been created as an object within the main() method. After creating the object you can then use the variables and methods of the object. An attempt to use the variables and methods of the class which do not have the static modifier without going through an object of the class is caught by the Java compiler at compile time and flagged as an error.
import java.io.*;
class HelloWorld {
int myInt; // this is a class variable that is unique to each object
static int myInt2; // this is a class variable shared by all objects of this class
static void main (String [] args) {
// this is the main entry point for this Java application
System.out.println ("Hello, World\n");
myInt2 = 14; // able to access the static int
HelloWorld myWorld = new HelloWorld();
myWorld.myInt = 32; // able to access non-static through an object
}
}
To be able to access them from your static methods they need to be static member variables, like this:
public class MyProgram7 {
static Scanner scan = new Scanner(System.in);
static int compareCount = 0;
static int low = 0;
static int high = 0;
static int mid = 0;
static int key = 0;
static Scanner temp;
static int[]list;
static String menu, outputString;
static int option = 1;
static boolean found = false;
public static void main (String[]args) throws IOException {
...
Let's analyze your program first..
In your program, your first method is main(), and keep it in mind it is the static method... Then you declare the local variable for that method (compareCount, low, high, etc..). The scope of this variable is only the declared method, regardless of it being a static or non static method. So you can't use those variables outside that method. This is the basic error u made.
Then we come to next point. You told static is killing you. (It may be killing you but it only gives life to your program!!) First you must understand the basic thing.
*Static method calls only the static method and use only the static variable.
*Static variable or static method are not dependent on any instance of that class. (i.e. If you change any state of the static variable it will reflect in all objects of the class)
*Because of this you call it as a class variable or a class method.
And a lot more is there about the "static" keyword.
I hope now you get the idea. First change the scope of the variable and declare it as a static (to be able to use it in static methods).
And the advice for you is: you misunderstood the idea of the scope of the variables and static functionalities. Get clear idea about that.
The very basic thing is static variables or static methods are at class level. Class level variables or methods gets loaded prior to instance level methods or variables.And obviously the thing which is not loaded can not be used. So java compiler not letting the things to be handled at run time resolves at compile time. That's why it is giving you error non-static things can not be referred from static context. You just need to read about Class Level Scope, Instance Level Scope and Local Scope.
Now you can add/use instances with in the method
public class Myprogram7 {
Scanner scan;
int compareCount = 0;
int low = 0;
int high = 0;
int mid = 0;
int key = 0;
Scanner temp;
int[]list;
String menu, outputString;
int option = 1;
boolean found = false;
private void readLine() {
}
private void findkey() {
}
private void printCount() {
}
public static void main(String[] args){
Myprogram7 myprg=new Myprogram7();
myprg.readLine();
myprg.findkey();
myprg.printCount();
}
}
I will try to explain the static thing to you. First of all static variables do not belong to any particular instance of the class. They are recognized with the name of the class. Static methods again do not belong again to any particular instance. They can access only static variables. Imagine you call MyClass.myMethod() and myMethod is a static method. If you use non-static variables inside the method, how the hell on earth would it know which variables to use? That's why you can use from static methods only static variables. I repeat again they do NOT belong to any particular instance.
The first thing is to know the difference between an instance of a class, and the class itself. A class models certain properties, and the behaviour of the whole in the context of those properties. An instance will define specific values for those properties.
Anything bound to the static keyword is available in the context of the class rather than in the context of an instance of the class
As a corollary to the above
variables within a method can not be static
static fields, and methods must be invoked using the class-name e.g. MyProgram7.main(...)
The lifetime of a static field/method is equivalent to the lifetime of your application
E.g.
Say, car has the property colour, and exhibits the behaviour 'motion'.
An instance of the car would be a Red Volkswagen Beetle in motion at 25kmph.
Now a static property of the car would be the number of wheels (4) on the road, and this would apply to all cars.
HTH
Before you call an instance method or instance variable It needs a object(Instance). When instance variable is called from static method compiler doesn't know which is the object this variable belongs to. Because static methods doesn't have an object (Only one copy always). When you call an instance variable or instance methods from instance method it refer the this object. It means the variable belongs to whatever object created and each object have it's own copy of instance methods and variables.
Static variables are marked as static and instance variables doesn't have specific keyword.
It is ClassLoader responsible to load the class files.Let's see what happens when we write our own classes.
Example 1:
class StaticTest {
static int a;
int b;
int c;
}
Now we can see that class "StaticTest" has 3 fields.But actually there is no existence of b,c member variable.But why ???. OK Lest's see. Here b,c are instance variable.Since instance variable gets the memory at the time of object creation. So here b,c are not getting any memory yet. That's why there is no existence of b,c. So There is only existence of a.
For ClassLoader it has only one information about a. ClassLoader yet not recognize b,c because it's object not instantiated yet.
Let's see another example:
Example 2:
class StaticTest {
public void display() {
System.out.println("Static Test");
}
public static void main(String []cmd) {
display();
}
}
Now if we try to compile this code compiler will give CE error.
CE: non-static method display() cannot be referenced from a static context.
Now For ClassLoader it looks like:
class StaticTest {
public static void main(String []cmd) {
display();
}
}
In Example 2 CE error is because we call non static method from a static context. So it is not possible for ClassLoader to recognize method display() at compile time.So compile time error is occurred.
This is bit diff to explain about static key word for all beginners.
You wil get to know it clearly when you work more with Classes and Objects.
|*| Static : Static items can be called with Class Name
If you observe in codes, Some functions are directly called with Class names like
NamCls.NamFnc();
System.out.println();
This is because NamFnc and println wil be declared using key word static before them.
|*| Non Static :Non Static items can be called with Class Variable
If its not static, you need a variable of the class,
put dot after the class variable and
then call function.
NamCls NamObjVar = new NamCls();
NamObjVar.NamFnc();
Below code explains you neatly
|*| Static and non Static function in class :
public class NamCls
{
public static void main(String[] args)
{
PlsPrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamObjVar.PrnFnc("Tst Txt");
}
static void PlsPrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
|*| Static and non Static Class inside a Class :
public class NamCls
{
public static void main(String[] args)
{
NamTicCls NamTicVaj = new NamTicCls();
NamTicVaj.PrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamNicCls NamNicVar = NamObjVar.new NamNicCls();
NamNicVar.PrnFnc("Tst Txt");
}
static class NamTicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
class NamNicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
}
In the Java programming language, the keyword static indicates that the particular member belongs to a type itself, rather than to an instance of that type.
This means that only one instance of that static member is created which is shared across all instances of the class.
So if you want to use your int count = 0; in static void main() , count variable must be declared as static
static int count = 0;
In this Program you want to use count, so declare count method as a static
class MyProgram<br>
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
Hear you can declare this method as a public private and protected also. If you are using this method you can create a secure application.
class MyProgram
{
static int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
This is because you do not create instance of the model class, you have to create instances every time you use non-static methods or variables.
you can easily fix this see below images
without making instance of class
My model class file
By just creating instance then use class non-static methods or variables easily error gone
I've written this test code:
class MyProgram
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
But it gives the following error:
Main.java:6: error: non-static variable count cannot be referenced from a static context
System.out.println(count);
^
How do I get my methods to recognize my class variables?
You must understand the difference between a class and an instance of that class. If you see a car on the street, you know immediately that it's a car even if you can't see which model or type. This is because you compare what you see with the class "car". The class contains which is similar to all cars. Think of it as a template or an idea.
At the same time, the car you see is an instance of the class "car" since it has all the properties which you expect: There is someone driving it, it has an engine, wheels.
So the class says "all cars have a color" and the instance says "this specific car is red".
In the OO world, you define the class and inside the class, you define a field of type Color. When the class is instantiated (when you create a specific instance), memory is reserved for the color and you can give this specific instance a color. Since these attributes are specific, they are non-static.
Static fields and methods are shared with all instances. They are for values which are specific to the class and not a specific instance. For methods, this usually are global helper methods (like Integer.parseInt()). For fields, it's usually constants (like car types, i.e. something where you have a limited set which doesn't change often).
To solve your problem, you need to instantiate an instance (create an object) of your class so the runtime can reserve memory for the instance (otherwise, different instances would overwrite each other which you don't want).
In your case, try this code as a starting block:
public static void main (String[] args)
{
try
{
MyProgram7 obj = new MyProgram7 ();
obj.run (args);
}
catch (Exception e)
{
e.printStackTrace ();
}
}
// instance variables here
public void run (String[] args) throws Exception
{
// put your code here
}
The new main() method creates an instance of the class it contains (sounds strange but since main() is created with the class instead of with the instance, it can do this) and then calls an instance method (run()).
Static fields and methods are connected to the class itself and not to its instances. If you have a class A, a 'normal' (usually called instance) method b, and a static method c, and you make an instance a of your class A, the calls to A.c() and a.b() are valid. Method c() has no idea which instance is connected, so it cannot use non-static fields.
The solution for you is that you either make your fields static or your methods non-static. Your main could look like this then:
class Programm {
public static void main(String[] args) {
Programm programm = new Programm();
programm.start();
}
public void start() {
// can now access non-static fields
}
}
The static keyword modifies the lifecycle of a method or variable within a class. A static method or variable is created at the time a class is loaded. A method or variable that is not declared as static is created only when the class is instantiated as an object for example by using the new operator.
The lifecycle of a class, in broad terms, is:
the source code for the class is written creating a template or
pattern or stamp which can then be used to
create an object with the new operator using the class to make an instance of the class as an actual object and then when done with the object
destroy the object reclaiming the resources it is holding such as memory during garbage collection.
In order to have an initial entry point for an application, Java has adopted the convention that the Java program must have a class that contains a method with an agreed upon or special name. This special method is called main(). Since the method must exist whether the class containing the main method has been instantiated or not, the main() method must be declared with the static modifier so that as soon as the class is loaded, the main() method is available.
The result is that when you start your Java application by a command line such as java helloworld a series of actions happen. First of all a Java Virtual Machine is started up and initialized. Next the helloworld.class file containing the compiled Java code is loaded into the Java Virtual Machine. Then the Java Virtual Machine looks for a method in the helloworld class that is called main(String [] args). this method must be static so that it will exist even though the class has not actually been instantiated as an object. The Java Virtual Machine does not create an instance of the class by creating an object from the class. It just loads the class and starts execution at the main() method.
So you need to create an instance of your class as an object and then you can access the methods and variables of the class that have not been declared with the static modifier. Once your Java program has started with the main() function you can then use any variables or methods that have the modifier of static since they exist as part of the class being loaded.
However, those variables and methods of the class which are outside of the main() method which do not have the static modifier can not be used until an instance of the class has been created as an object within the main() method. After creating the object you can then use the variables and methods of the object. An attempt to use the variables and methods of the class which do not have the static modifier without going through an object of the class is caught by the Java compiler at compile time and flagged as an error.
import java.io.*;
class HelloWorld {
int myInt; // this is a class variable that is unique to each object
static int myInt2; // this is a class variable shared by all objects of this class
static void main (String [] args) {
// this is the main entry point for this Java application
System.out.println ("Hello, World\n");
myInt2 = 14; // able to access the static int
HelloWorld myWorld = new HelloWorld();
myWorld.myInt = 32; // able to access non-static through an object
}
}
To be able to access them from your static methods they need to be static member variables, like this:
public class MyProgram7 {
static Scanner scan = new Scanner(System.in);
static int compareCount = 0;
static int low = 0;
static int high = 0;
static int mid = 0;
static int key = 0;
static Scanner temp;
static int[]list;
static String menu, outputString;
static int option = 1;
static boolean found = false;
public static void main (String[]args) throws IOException {
...
Let's analyze your program first..
In your program, your first method is main(), and keep it in mind it is the static method... Then you declare the local variable for that method (compareCount, low, high, etc..). The scope of this variable is only the declared method, regardless of it being a static or non static method. So you can't use those variables outside that method. This is the basic error u made.
Then we come to next point. You told static is killing you. (It may be killing you but it only gives life to your program!!) First you must understand the basic thing.
*Static method calls only the static method and use only the static variable.
*Static variable or static method are not dependent on any instance of that class. (i.e. If you change any state of the static variable it will reflect in all objects of the class)
*Because of this you call it as a class variable or a class method.
And a lot more is there about the "static" keyword.
I hope now you get the idea. First change the scope of the variable and declare it as a static (to be able to use it in static methods).
And the advice for you is: you misunderstood the idea of the scope of the variables and static functionalities. Get clear idea about that.
The very basic thing is static variables or static methods are at class level. Class level variables or methods gets loaded prior to instance level methods or variables.And obviously the thing which is not loaded can not be used. So java compiler not letting the things to be handled at run time resolves at compile time. That's why it is giving you error non-static things can not be referred from static context. You just need to read about Class Level Scope, Instance Level Scope and Local Scope.
Now you can add/use instances with in the method
public class Myprogram7 {
Scanner scan;
int compareCount = 0;
int low = 0;
int high = 0;
int mid = 0;
int key = 0;
Scanner temp;
int[]list;
String menu, outputString;
int option = 1;
boolean found = false;
private void readLine() {
}
private void findkey() {
}
private void printCount() {
}
public static void main(String[] args){
Myprogram7 myprg=new Myprogram7();
myprg.readLine();
myprg.findkey();
myprg.printCount();
}
}
I will try to explain the static thing to you. First of all static variables do not belong to any particular instance of the class. They are recognized with the name of the class. Static methods again do not belong again to any particular instance. They can access only static variables. Imagine you call MyClass.myMethod() and myMethod is a static method. If you use non-static variables inside the method, how the hell on earth would it know which variables to use? That's why you can use from static methods only static variables. I repeat again they do NOT belong to any particular instance.
The first thing is to know the difference between an instance of a class, and the class itself. A class models certain properties, and the behaviour of the whole in the context of those properties. An instance will define specific values for those properties.
Anything bound to the static keyword is available in the context of the class rather than in the context of an instance of the class
As a corollary to the above
variables within a method can not be static
static fields, and methods must be invoked using the class-name e.g. MyProgram7.main(...)
The lifetime of a static field/method is equivalent to the lifetime of your application
E.g.
Say, car has the property colour, and exhibits the behaviour 'motion'.
An instance of the car would be a Red Volkswagen Beetle in motion at 25kmph.
Now a static property of the car would be the number of wheels (4) on the road, and this would apply to all cars.
HTH
Before you call an instance method or instance variable It needs a object(Instance). When instance variable is called from static method compiler doesn't know which is the object this variable belongs to. Because static methods doesn't have an object (Only one copy always). When you call an instance variable or instance methods from instance method it refer the this object. It means the variable belongs to whatever object created and each object have it's own copy of instance methods and variables.
Static variables are marked as static and instance variables doesn't have specific keyword.
It is ClassLoader responsible to load the class files.Let's see what happens when we write our own classes.
Example 1:
class StaticTest {
static int a;
int b;
int c;
}
Now we can see that class "StaticTest" has 3 fields.But actually there is no existence of b,c member variable.But why ???. OK Lest's see. Here b,c are instance variable.Since instance variable gets the memory at the time of object creation. So here b,c are not getting any memory yet. That's why there is no existence of b,c. So There is only existence of a.
For ClassLoader it has only one information about a. ClassLoader yet not recognize b,c because it's object not instantiated yet.
Let's see another example:
Example 2:
class StaticTest {
public void display() {
System.out.println("Static Test");
}
public static void main(String []cmd) {
display();
}
}
Now if we try to compile this code compiler will give CE error.
CE: non-static method display() cannot be referenced from a static context.
Now For ClassLoader it looks like:
class StaticTest {
public static void main(String []cmd) {
display();
}
}
In Example 2 CE error is because we call non static method from a static context. So it is not possible for ClassLoader to recognize method display() at compile time.So compile time error is occurred.
This is bit diff to explain about static key word for all beginners.
You wil get to know it clearly when you work more with Classes and Objects.
|*| Static : Static items can be called with Class Name
If you observe in codes, Some functions are directly called with Class names like
NamCls.NamFnc();
System.out.println();
This is because NamFnc and println wil be declared using key word static before them.
|*| Non Static :Non Static items can be called with Class Variable
If its not static, you need a variable of the class,
put dot after the class variable and
then call function.
NamCls NamObjVar = new NamCls();
NamObjVar.NamFnc();
Below code explains you neatly
|*| Static and non Static function in class :
public class NamCls
{
public static void main(String[] args)
{
PlsPrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamObjVar.PrnFnc("Tst Txt");
}
static void PlsPrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
|*| Static and non Static Class inside a Class :
public class NamCls
{
public static void main(String[] args)
{
NamTicCls NamTicVaj = new NamTicCls();
NamTicVaj.PrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamNicCls NamNicVar = NamObjVar.new NamNicCls();
NamNicVar.PrnFnc("Tst Txt");
}
static class NamTicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
class NamNicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
}
In the Java programming language, the keyword static indicates that the particular member belongs to a type itself, rather than to an instance of that type.
This means that only one instance of that static member is created which is shared across all instances of the class.
So if you want to use your int count = 0; in static void main() , count variable must be declared as static
static int count = 0;
In this Program you want to use count, so declare count method as a static
class MyProgram<br>
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
Hear you can declare this method as a public private and protected also. If you are using this method you can create a secure application.
class MyProgram
{
static int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
This is because you do not create instance of the model class, you have to create instances every time you use non-static methods or variables.
you can easily fix this see below images
without making instance of class
My model class file
By just creating instance then use class non-static methods or variables easily error gone
I have this code in java I write it by netbeans
class sample
{
public static int x;
public int y;
sample()
{
x=0;
}
}
public class JavaApplication1 {
/**
* #param args the command line arguments
*/
sample cchild=new sample();
public static void main(String[] args) {
// TODO code application logic here
sample.x=0;
cchild.x=9; // here error
}
explain the sample :
I make composition to class sample , class sample contain static variable x , But when I try to access to static variable x from the instance cchild in static method the compiler make error,
so in java I can not access to object in static methode even the instance contain static member ???
The first thing you need to understand is that static members belong to a class and not an instance and can therefore be accessed directly without the need to create a reference to an instance of the class. The following statement accesses the static member x in class sample where sample is the class name and x is the static member in sample :
sample.x=0;
The following statement on the other hand does not work because
the reference cchild is not static and is thus an instance field while main is a static method. An instance field cannot be accessed in a static method without a reference to an instance of the class.
cchild.x=9
For the above statement to work, you either declare cchild as static in JavaApplication1 or create an instance of JavaApplication1 in main as shown below :
JavaApplication1 instanceOfJApp = new JavaApplication1();
instanceOfJApp.cchild.x=9;
This should work. You need to declare the variable cchild to be a static member of the JavaApplicaiton1 class to be able to access it statically.
class sample
{
public static int x;
public int y;
sample()
{
x=0;
}
}
public class JavaApplication1 {
// NEW BIT - by making this variable static we can now access it without needing an instance of the object.
static sample cchild=new sample();
public static void main(String[] args) {
sample.x=0;
cchild.x=9;
}
}
Static in Java means it is a property of the class itself and not a property of an instance object of that class's type. When using non-static properties you need to have created an object of that class's type by calling a constructor and then you can use that object's reference to call non-static methods and access non-static variables. If you don't have a copy of an object of that type then you can only call the static methods and access the static variables.
The original didn't work because although you were trying to access the static variable from a static context (inside the main method which is static) you were creating the variable you used to access the static variable (cchild) in a non-static context (in the class definition). By not labelling the cchild variable 'static' it becomes an instance variable of the JavaApplication1 class and so can only be used if you create an instance of the JavaApplication1 class by calling a constructor, and not in the main method which is created statically.
I have suggested here that you change the variable to be static so that you can access it. I think this is the easiest way for you to make progress. However, in general, if you get stuck needing to make a change like this it probably shows that you need to think more about which members need to be static and which need to be on the instance object and so just making the variable static might not always be the best thing to do.
There are a few other things you might do differently in this code example. The first is that I would suggest that you use the Java naming convention of starting the name of your classes with a capital letter (Sample instead of sample in this case) otherwise they do not look like class names to Java people.
There are 2 things you can do to fix your problem:
Make cchild static
Move the declaration of cchild to your main method
It's because invoking
static void main(String[] args){
}
doesn't make the JavaApplication1 instance.