Accessing instance variables from another class from a static method - java

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.

Related

How to access or use in a condition the variable from another class

How to access or use in a condition the variable from another class ??
I have a declared variable makol in kstemmer class and i want to use that in stemmer class..
public class Kstemmer {
private int makol=0;
}
//and this for the stemmer class
public Stemmer() {
if (makol==0){
System.out.println("avid");
}
}
A variable that is private cannot be used from another class. You have to make it public - if they are in the same package you may also leave away both private and public.
Also, that variable is not static. If you want to use it globally, you have to use static int makol = 0; and then reference it with Kstemmer.makol.
Alternatively you can instanciate an Object of Kstemmer with Kstemmer someObject = new Kstemmer() and access the variable with someObject.makol.
Depending on use case, you would use getters and setters instead of making the variable public. Non-final variables should almost always be used with getters and setters.

How to access non-static variables & methods from a different class

I do not quite understand the use of "static" properly.
I have a class which includes variables that I want to access from a different class.
However, when I try to access this getter method from the different class I get an error stating:
"non-static method getAccNumber() cannot be referenced from a static context."
So, how can I find this variable's value without making it static. The problem with this is if I make it static, every instance of this object overwrites the previous value.
So they all end up with the same account number in this case.
Let me explain in more detail:
I have a Class called Account, which contains a variable called accountNumber, and a getter method called getAccNumber().
I have a second class called AccountList which is a separate arraylist class to store instances of Account. I want to create a method to remove an element based upon its accountNumber. So I'm searching and using getAccnumber() within the AccountList class to compare with a user parameter and removing if correct!
But I can't use this method without making it static!!
Any help/explanation would be greatly appreciated :)
This is what I am trying to do:
public boolean removeAccount(String AccountNumber)
{
for(int index = 0; index < accounts.size(); index++)
{
if (AccountNumber.equals(Account.getAccNumber()))
{
accounts.remove(index);
return true;
}
}
return false;
}
Thank you!
Let's take an example where you have
public class A {
static void sayHi() { System.out.println("Hi");
//Other stuff
}
and
public class B {
void sayHi() { System.out.println("Hi");
//Other stuff
}
Then
public class C {
public C() {
A.sayHi(); //Possible since function is static : no instantiation is needed.
B.sayHi(); //Impossible : you need to instantiate B class first
}
You can check out this link for a short definition:
Static Method Definition
If you declare a variable as static, it will not be unique for each instance of the class. If you declare the variable as private only, then you can create getter and setter methods that will allow you to access the variable after you have created an instance of the class. For example, if you have classA and classB and you are working in classB and want the private int size of classA:
classA a = new ClassA();
int size = a.getSize(); //getSize() returns the private int size of classA
A static variable is one that lives with the class itself. A non-static variable is unique to each instance of that class (i.e., each object built from that class.) A static variable you can access as a property of the class, like:
SomeclassIMadeUp.numberOfFish;
so if you change the numberOfFish property for that class, anywhere you reference it, you see the change (as you've noticed.)
To have one unique to each instance, don't declare the variable as static and then add a getter and/or setter method to access it.
like
private int numberOfFish;
public int getNumberOfFish() { return (numberOfFish); }
So to your question...
Ocean pacific = new Ocean();
pacific.water = Ocean.salty; // <-- Copying the value from a static variable in the class Ocean
// to the instance variable in the object pacific (which is of Ocean class).
pacific.setNumberOfFish(1000000000);
Octopus o = new Octopus();
o.diningOpportunities = pacific.getNumberOfFish(); // <-- Calls the public method to return a
// value from the instance variable in the object pacific.

Using a non-static variable in a static method 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.

Can't access public non-static class attribute from secondary class

I have the following two classes:
public class Class1
{
public Class1 randomvariable; // Variable declared
public static void main(String[] args)
{
randomvariable = new Class1(); // Variable initialized
}
}
public class Class2
{
public static void ranMethod()
{
randomvariable.getSomething(); // I can't access the member "randomvariable" here even though it's public and it's in the same project?
}
}
I am very certain that it's a very fundamental thing I'm missing here, but what am I actually missing? The Class1 member "randomvariable" is public and so is the class and both classes are in the same project.
What do I have to do to fix this problem?
There are two problems:
Firstly, you're trying to assign a value to randomvariable from main, without there being an instance of Class1. This would be okay in an instance method, as randomvariable would be implicitly this.randomvariable - but this is a static method.
Secondly, you're trying to read the value from Class2.ranMethod, again without there being an instance of Class1 involved.
It's important that you understand what an instance variable is. It's a value associated with a particular instance of a class. So if you had a class called Person, you might have a variable called name. Now in Class2.ranMethod, you'd effectively be writing:
name.getSomething();
That makes no sense - firstly there's nothing associating this code with Person at all, and secondly it doesn't say which person is involved.
Likewise within the main method - there's no instance, so you haven't got the context.
Here's an alternative program which does work, so you can see the difference:
public class Person {
// In real code you should almost *never* have public variables
// like this. It would normally be private, and you'd expose
// a public getName() method. It might be final, too, with the value
// assigned in the constructor.
public String name;
public static void main(String[] args) {
Person x = new Person();
x.name = "Fred";
PersonPresenter.displayPerson(x);
}
}
class PersonPresenter {
// In a real system this would probably be an instance method
public static void displayPerson(Person person) {
System.out.println("I present to you: " + person.name);
}
}
As you can tell by the comments, this still isn't ideal code - but I wanted to stay fairly close to your original code.
However, this now works: main is trying to set the value of an instance variable for a particular instance, and likewise presentPerson is given a reference to an instance as a parameter, so it can find out the value of the name variable for that instance.
When you try to access randomvariable you have to specify where it lives. Since its a non-static class field, you need an instance of Class1 in order to have a randomvariable. For instance:
Class1 randomclass;
randomclass.randomvariable.getSomething();
If it were a static field instead, meaning that only one exists per class instead of one per instance, you could access it with the class name:
Class1.randomvariable.getSomething();

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