0

So I have a class with an int attribute which can't be static:

public class GetterId{ int id = 42; public int getId() { return id; } public void setId(int id) { this.id = id; } } 

And I'd like to have an access to this "id" attribute from another class, like:

public class MainActivity { int id_bis; id_bis = GetterID.getId(); } 

But it can't be this way because the method getId() and the attribute from the GetterId class are non static...

Is there any solutions to this problem?

1
  • The question doesn't make sense. The class doesn't have any non-static attributes. Only instances have those. You want the attribute, you need an instance. Commented Sep 15, 2015 at 21:10

3 Answers 3

1

Create a object of the GetterId class in the MainActivity class. With this object you can access variables and methods of the the GetterId class.

GetterId object = new GetterId(); object.getId(); object.setId(34); int id = object.id; 
Sign up to request clarification or add additional context in comments.

3 Comments

What if MainActivity and GetterId class are in different packages?
just import the package name of the class. see this thread stackoverflow.com/questions/3480389/…
0

You have to create an object of type GetterId and then call getId from this object.

 GetterId obj = new GetterId(); obj.getId(); 

This is because your id has to be associated with an object since each object can have a different id. I guess this is why you have a setter function for the id. So for your program to retrieve the correct id it has to have a reference to an object of type GetterId.

3 Comments

But what if I want to get the value of the id and not the object itself?
To get the id you have to have an instance of GetterId to call getId() on, assuming your class is set up like it is in your question.
@Chris Then you have to make it static. There is no other way to access a value without creating an object unless you make it static. Static means that all object from that class share the same value this is why you can access it via the class name. But if each object has its own value then you have to access it through the object itself otherwise it won't be able to give you the correct value.
0

you could create a singleton class and use getInstance to get an instance of that object

example:

public final class GetterId { private static GetterId instance; private GetterId(){} public static GetterId getInstance(){ if (instance == null) { synchronized (GetterId.class) { if (instance == null) { instance = new GetterId(); } } } return instance; } } 

Then anytime you need to reference that object just call

GetterId getter = GetterId.getInstance() id_bis = getter.getId(); 

that should give you the same reference everywhere and you can use the object as normal

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.