Using a non-static variable in a static method JAVA - java

So I am writing a very large java code, within this code I want it to output files in a particular file format. In this instance it is going to be a simple .txt file.
The data I am outputting is a series of coordinates, these coordinates have undergone rotation using an angle that is determined by the user prior to this code section.
The code to write the file is obviously in a static method but the angle I am calling is a non-static variable... how do I call this and get it to work?

Basically you have to pass an instance of the object containing the non-static variable to the static function and access it there.
That would look something like this:
public class ObjectToBeWritten {
private int nonStaticVariable;
public ObjectToBeWritten() {
// ...
}
public int getNonStaticVariable() {
return nonStaticVariable;
}
public static void outputToTxt(ObjectToBeWritten object) {
nonStaticVariable = object.getNonStaticVariable();
// ...
}
}
Then you just call ObjectToBeWritten.outputToTxt(object) with the object that contains the non-static variable.

Non static means that it belongs to some class instance(object). So pass this object to your static method and/or create those objects inside it.

you should know non-static method belongs to Object ,but static method belongs to Class.Therefore the getNonStaticVariables method and nonStaticVariable should be static or change the outputToTxt to non-static.

My first thought is that perhaps either your non-static variable or your static method belong somewhere else.
When a class hold variable, non-static contents, it's probably a bad idea to provide static accessor functions that use that variable. I think the best solution is to separate the two, giving the responsibility of storing the mutable data in some Data Provider class that can provide a DEFENSIVE COPY of this variable. Perhaps you don't see the need for it because your example deals with a primitive value. But, if you were to change that to some object reference, you could run into all sorts of problems; one of which is that your code will not be thread-safe.
public class MyDataProvider {
private Object nonStaticVariable;
public MyDataProvider () {
// ...
}
public Object getNonStaticVariable() {
Object copy = new Object();
// copy the internals from nonStaticVariable to copy
return copy;
}
}
Then, your utility class can use the copy of nonStaticVariable to do its work...
public class MyUtilityClass {
public static void outputToTxt(Object nonStaticVariableCopy) {
// do your work
}
}
This solution solves all those problems and is much more robust:
Allows a non-static variable to be used by a static method
Your code will be thread-safe because you are using a copy of the non-static variable instead of the original variable.
Separation of concerns: Your utility class doesn't store any variables; thus all methods of the utility class can be static (like Java's Math class), and your Data Provider can be the container that holds your variables.

Related

Why make an object for Main class, for the methods to work?

I was facing an error before, but when I made an object in this class the and called for the method, it worked flawlessly. Any explanation? Do I always have to make an object to call for methods outside of the main method (but in the same class)?
here:
public class A{
public static void main(String[] args){
A myObj= new A();
System.out.println(myObj.lets(2));
}
public int lets(int x){
return x;
}
}
You need to understand static. It associates a method or field to the class itself (instead of a particular instance of a class). When the program starts executing the JVM doesn't instantiate an instance of A before calling main (because main is static and because there are no particular instances of A to use); this makes it a global and an entry point. To invoke lets you would need an A (as you found), or to make it static (and you could also limit its' visibility) in turn
private static int lets(int x) {
return x;
}
And then
System.out.println(lets(2));
is sufficient. We could also make it generic like
private static <T> T lets(T x) {
return x;
}
and then invoke it with any type (although the type must still override toString() for the result to be particularly useful when used with System.out.println).
There are a importance concept to consider an is static concept. In your example you have to create an instance of your class because the main method is static and it only "operate" with other statics methods or variable. Remember that when you instantiate a class you are creating a copy of that class an storing that copy in the instance variable, so as the copy (That was create inside of a static method in your case) is also static so it can access the method which is not static in that context.
In order to not create an instance and access to your method you need to make your lets method static(due to the explanation abode)
public static int lets(int x){
return x;
}
And in your main you don't need to instantiate the class to access to this method.
public static void main(String[] args){
System.out.println(lets(2));
}
Check this guide about static in java: https://www.baeldung.com/java-static
Hope this help!

Why using public static methods in Java?

If I understand the meaning of each keyword correctly, public means the method is accessible by anybody(instances of the class, direct call of the method, etc), while static means that the method can only be accessed inside the class(not even the instances of the class). That said, the public keyword is no use in this situation as the method can only be used inside the class. I wrote a little program to test it out and I got no errors or warnings without putting the public key word in front of the method. Can anyone please explain why public static methods are sometimes use? (e.g. public static void main(String[] args))
Thank you in advance!
Static methods mean you do not need to instantiate the class to call the method, it does't mean you cannot call it from anywhere you want in the application.
Others have already explained the right meaning of static.
Can anyone please explain why public static methods are sometimes use?
Maybe the most famous example is the public static void main method - the standard entry point for java programs.
It is public because it needs to be called from the outside world.
It is static because it won't make sanse to start a program from an object instance.
Another good examle is a utility class, one that only holds static methods for use of other classes. It dosen't need to be instantiated (sometimes it even can't), but rather supply a bounch of "static" routines to perform, routines that does not depend on a state of an object. The output is a direct function of the input (ofcourse, it might also be subject to other global state from outside). this is actually why it is called static.
That said, the static keyword is not always used because you want to have access to some members in a class without instantiating it, but rather because it makes sense. You keep a property that is shared among all instances in one place, instead of holding copies of it in each instance.
That leads to a third common use of public static (or even public static final) - the definition of constants.
A public static method is a method that does not need an instance of the class to run and can be run from anywhere. Typically it is used for some utility function that does not use the member variables of a class and is self contained in its logic.
The code below chooses a path to store an image based on the image file name so that the many images are stored in a tree of small folders.
public static String getImagePathString(String key){
String res = key.substring(3, 4)+File.separator+
key.substring(2, 3)+File.separator+
key.substring(1, 2)+File.separator+
key.substring(0, 1);
return res;
}
It needs no other information (it could do with a safety check on the size of key)
A quick guide to some of the options...
public class Foo {
public static void doo() {
}
private static void dont() {
}
public Foo() {
doo(); // this works
dont(); // this works
Foo.doo(); // this works
Foo.dont(); // this works
this.doo(); // this works but is silly - its just Foo.doo();
this.dont(); // this works but is silly - its just Foo.dont();
}
public static void main(String[] args) {
doo(); // this works
dont(); // this works
Foo.doo(); // this works
Foo.dont(); // this works
Foo foo = new Foo();
foo.doo(); // this works but is silly - its just Foo.doo();
}
}
public class Another {
public static void main(String[] args) {
Foo.doo(); // this works
Foo.dont(); // this DOESN'T work. dont is private
doo(); // this DOESN'T work. where is doo()? I cant find it?
}
}

Accessing instance variables from another class from a static method

I have the following code:
public static boolean isRelated(Animal first, Animal second){
boolean result=false;
if(first(parentA).equals(second(parentA)))
result=true;
return result;
}
basically, I need to be able to access the parent A instance variable that is in the Animal class from this static method.
I understand that, to access instance variables in a static method, you need to create an object but I already have 2 brought in.(Parent A and Parent B)
Could you guys tell me what the problem here is?
In order to access instance variable, you need to use an instance. You don't have to create it each time you need it, as long as you have one.
And for your code:
if(first.getParentA().equals(second.getParentA()))
In this case you need to make sure than first.getParentA() isn't null before comparing (or else you'll get NPE)
if(first(parentA).equals(second(parentA)))
basically, I need to be able to access the parent A instance variable that is in the Animal class from this static method.
That is not the correct syntax to access instance members
should be
if(first.parentA.equals(second.parentA))
More over use setters and getters to access the data such that
public class Animal {
private String parentA;
// code
public String getParentA() {
return parentA;
}
public void setParentA(String parentA) {
this.parentA = parentA;
}
}
}
Then use the line if(first.getParentA().equals(second.getParentA()))
Static methods are created in method area, and is the first to be created. Instance variables are created in heap after static methods are created. Hence, accessing instance variables directly is not possible. Always make use of an object to access such variables.

Use static method or not?

Hi i have a web service in java, in which i have a class that has different methods that modify the string that the client sends and return it back according to the type of sting he wants. So based on the string type requirement a method is called..
like
class Test{
public static String a(String z)
{
// do stuff and return;
}
public static String b(String z)
{
// do stuff and return;
}
}
so if an array of like 10000 requests comes, these methods are called 10000 times, i want to know that should these methods be taken as static or NOT(i should create a global object of this class in my main web service class and call these methods) ?
I don't think you need to make method as static, if you can access the method within the object then you should (avoid static as much as possible).This improve code performance (in terms of memory utilization).
What's the compelling reason that these methods be static? If you need static methods, then create those. Otherwise, from a design standpoint, stick to non-static methods. You can't override static methods (though you can hide 'em.)
And there's this:
In Java, is there any disadvantage to static methods on a class?
You can use a static method if the method behaves the same for all cases. If the methods just does some work on the string supplied as a parameter and the behavior is the same for all instances, you can.
Again, you can also make a singleton out of it & call the methods through the UNIQUE_INSTANCE.
Something like:
public class Test {
private static final Test UNIQUE_INSTANCE = new Test();
private Test() {
}
public static final Test getUniqueInstance() {
return UNIQUE_INSTANCE;
}
public final String a(String z) {
// do stuff and return;
}
public final String b(String z) {
// do stuff and return;
}
}
Then you can do >>
Test.getUniqueInstance().a("Hello");
Test.getUniqueInstance().b("World");
If there is not any resource which is shared among the threads then there is not harm to use any static method.
Yes, there should be a Static modifier since there is no interaction between the different methods or functions, and the result is returned in the very same method. the "Static" word is to define a class variable or method that can be accessed without instantiating an object of such class.
if you do not intend to instantiate the class, and just need to use the methods inside, "Static" is the correct way to go, and set the class constructor to private.

Is there a way to access the variables of the calling class in a method?

At present I have a class that is calling the static method of a different class. What I am trying to do however is have the static method change a variable of the calling class, is that possible?
Example code:
public class exClass {
private int aVariable;
public exClass() {
othClass.aMethod();
}
}
public class othClass {
static void aMethod() {
// stuff happens, preferably stuff that
// allows me to change exClass.aVariable
}
}​
So what I would like to know is, if there is a way to access aVariable of the instance of exClass that is calling othClass. Other than using a return statement, obviously.
Not if aClass doesn't expose that variable. This is what encapsulation and information hiding are about: if the designer of the class makes a variable private, then only the component that owns it can modify or access it.
Of course, the dirty little secret in Java is that reflection can get you around any private restriction.
But you should not resort to that. You should design your classes appropriately and respect the designs of others.
You can pass this as a parameter to the second function.
public class exClass {
public int aVariable;
public exClass()
{
othClass.aMethod(this);
}
}
public class othClass{
static void aMethod(exClass x)
{
x.aVariable = 0; //or call a setter if you want to keep the member private
}
}
you should gave the static method in othClass the instance of exClass like othClass.aMethod(this), then you can change the variable of that instance, or make the variable static if you dont need an instance

Categories