-2

As i am new in java. I have searched about static mean in java and i got solution on stack overflow here but when i compiled it it is showing error. Can anybody suggest Where i am mistaking ?

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
}

enter image description here

Akash Singh Sengar
  • 499
  • 1
  • 8
  • 26

2 Answers2

3

well in class level you can only define attributes of that class, cant do any processing which you are doing in classA and classB. Processing can only be done in method.

Just add main method make objects there

public class Hello
{
    // value / method
    public static String staticValue;
    public String nonStaticValue;

    public void main(String[] args){

      Hello hello = new Hello();
      Hello.staticValue = "abc";
      hello.nonStaticValue = "xyz";

      Hello hello2 = new Hello(); // here staticValue = "abc"
      Hello.staticValue; // will have value of "abc"
      hello2.nonStaticValue; // will have value of null
    }
}

Main method is entry point of any program in java. Dont worry if you are confused where this main method is called.

Roohi Zuwairiyah
  • 363
  • 3
  • 15
  • 1
    or have it in a static code block – Scary Wombat Jun 02 '17 at 06:35
  • This doesn´t compile, the variable access `hello2.staticValue;` can´t just standalone (i know you probably just forgot to copy the assignment from above) – SomeJavaGuy Jun 02 '17 at 06:36
  • I edited it, it should work now. You were accessing static variable using object reference. Static variables can only be accessed using class reference. – Mohammad Mudassir Jun 02 '17 at 06:39
  • @MohammadMudassir that´s not right, it works also with the variable. It´s a bad design decission by the Java developer, but it works – SomeJavaGuy Jun 02 '17 at 06:41
  • "_Processing can only be done in method._" I disagree with that. And this should be in the constructor of `A` and `B` to match OP's code – AxelH Jun 02 '17 at 07:10
1

First of all, to run Java files you need a public class which contains the main method. Changing variable content can only be done in a method.

public class Hello(){
    public static String staticValue;
    public String nonStaticValue;
    public static void main(String[] args){
    Hello hello = new Hello();
    Hello.staticValue = "abc";
    hello.nonStaticValue = "xyz";
    Hello hello2 = new Hello();
    System.out.println(hello2.staticValue);
    System.out.println(hello2.nonStaticValue);
    }
}
Unheilig
  • 16,196
  • 193
  • 68
  • 98
sjana
  • 64
  • 1
  • 10