Is it possible to avoid using "static" when call variable from another class?

Viewed 66

Is it able to avoid using "static" when call variable from another class? thank you very much

Here is my code.

class Hello {
  public static String say = "Hello World";  //I using static       
  public void born() {                    
    System.out.println(say);
  }
}

public class SayHello extends Hello {
  public static void main(String[] args) {
    Hello myHello = new Hello();
    myHello.born();
    System.out.println(say);

  }

The Output:

Hello World
Hello World

If I use public String say = "Hello World";

it output Hello World null

AnyIdea to avoid using "static" when call variable from another class? thank you very much

4 Answers

A static variable is common to all the instances (or objects) of the class because it is a class level variable. In other words you can say that only a single copy of static variable is created and shared among all the instances of the class.

So if you don't want to use static, then you can't use it in the other instances of class.

Yes, if you don't declare it static you can reference it from an instance: myHello.say. It is the same as for calling a function.

public class SayHello extends Hello {
  public static void main(String[] args) {
    Hello myHello = new Hello();
    myHello.born();
    System.out.println(myHello.say);
  }
}

For a constant, ie. a String that never changes and is the same for all instances of the class, it makes sense to declare it static and use it as such.

If you don't mark the string as static you will get a compilation error because when you do System.out.println(say) in the main method you are using say in a static context (since the main method must be static).

If you remove System.out.println(say); and just leave myHello.born(); then there's no need for say to be static because you'll only be using it from non-static methods (i.e. the born() method). You can see it in this example where I commented that line and defined say as not being static.

Another option would be to make the println like this, since the variable is public: System.out.println(myHello.say);

If you remove the static, it will not compile. Static fields can be marked private, if you want to hide them. So then they are reachable by all instances of the class Hello only. The proper way of modifying or getting would be:

class Main extends Hello {
  public static void main(String[] args) throws Exception {
    Hello myHello = new Hello();
    myHello.born();
    // System.out.println(say); //doesn't allow access
    // System.out.println(Hello.say); //doesn't allow access
    System.out.println(myHello.getSay());
  }
 
}

class Hello {
  private static String say = "Hello World";  //private      
  public void born() {                    
    System.out.println(say);
  }

 public String getSay() {
  return say;
 }
}
Related