How Do I Access One Variable From Another Class? - java

I am not by my programming computer right now, so I can't post the code. I've been taking online lessons that I bought from Udemy so I'm still learning a lot.
I've looked at a decent number of posts, but the code they posts seem so long and complicated that it gets confusing. I have tried using a static variable, but the data needs to be changeable.
This is in android studios.
How do I access the data from one class in another class?
Class One:
//Class name is "ClassOne"
//Integer is an int named myNum and is equal to 1.
Class Two:
//Class name is "ClassTwo"
//I want my new int, myNewInt, to be equal to myNum.

If the field myNum is declared as public, you can access it by
any other class by typing the name of the object instance.myNu
If the filed myNum is declared as public static, you can access it
from any other class by typing the name of the class.myNum
If the field myNum is private, you need getters and setters, namely,
methods to access the file from an instance of the class that
contains it. Google them to get up to speed on why they're useful and
why you should use them.
Ex.
//public
ClassOne instance = new ClassOne();
ClassTwo instante2 = new ClassTwo();
instance2.myNewInt = instance.myNum;
//public static
ClassTwo instante2 = new ClassTwo();
instance2.myNewInt = ClassOne.myNum;
//getter
ClassOne instance = new ClassOne();
ClassTwo instante2 = new ClassTwo();
instance2.myNewInt = instance.getMyNum();
//and inside of ClassOne you'll have
private int MyNum = 5;
public getMyNum(){
return MyNum;
}
Note:
If the variable was only declared locally (inside the body of one of ClassOne's methods), you're gonna need to assign it to a filed, so that you can later access it from other classes.
Reading Material:
Getters and Setters
Access modifiers

You should create a getter method in the first class
public int getMyNum(){
return myNum;
}
In the second class you should have a setter method for the field myNewInt
public void setMyNewInt(int num){ this.myNewInt = num; }
And wherever you are running the code
myObject2.setMyNewInt(myObject1.getMyNum());
Sorry if there's any mistake, wrote this on the phone in a bus xD

There are couple of ways to do it.
Create an object of Class One and access fields via that object or create getter and setter methods.
Declare the field as static and access directly.

Related

Java class instance outside main method

I am studying Java, and I am a beginner.
I tried to create three classes (in the same package).
One with main method (JavaApp1), another that I've called "JavaClass1" and the last class "JavaClass2".
Here's the JavaClass1's code:
public class JavaClass1 {
public int var1;
public int var2;
}
JavaClass2's code:
public class JavaClass2 {
JavaClass1 ogg = new JavaClass1();
ogg.var1 = 4;
ogg.var2 = 7;
}
In the JavaClass2, Netbeans show me two error, related to the assignments (JavaClass1.var1 and JavaClass.var2) "Package ogg does not exist. expected.
But if i Create the Class instance and attributes assignments inside the main method, there are no problems. Why?
You cannot set the field of an object outside a method.
ogg.var1 = 4;
ogg.var2 = 7;
has to be inside some method.
Classes consist of class fields (like your var1 in the first class) and methods. Methods "do the work", i.e. execute code. You can initialize fields, but all other code has to be inside a method.
One more note: It is very bad style to have public fields. Please write getters and setters instead.
Try using getter and setters,
read this
http://www.tutorialspoint.com/java/java_encapsulation.htm

Accessing instance methods that are two objects deep in Java

Say I have a class, Bobject with an instance variable and method to retrieve it:
public class Bobject {
private int bInstVar;
public Bobject() {
bInstVar = 1;
}
getBInstVar() {
return bInstVar;
}
}
If I create a class Cobject representing an object that is an array of Bobject like so:
public class Cobject {
public Bobject[] cInstVar;
public Cobject() {
cInstVar = new Bobject[2]; //arbitrary array size for simplicity of the question
for (i = 0; i <= 2; i++;) {
cInstVar[i] = new Bobject();
}
}
}
If I have a main program that creates a Cobject and attempts to access methods of the references to the Bobjects stored in each element, I find that I have to first access the Cobject instance variable, cInstVar. This means cInstVar has to be public for main() to get at it without a method if main is outside of the package or class.
My question is, is there a way around doing this:?
Cobject c = new Cobject;
c.cObject1[0].getBInstVar();
Instead, I want to have an object that is an array of another class and get to that classes instance methods easier like so:
Cobject c = new Cobject;
c.getBInstVar(); // error says 'array required, but Cobject found'
I'm still pretty new to Java (and stackExchange) so please forgive me if anything I've presented is unclear. Thanks in advance!
As a general rule of thumb class variable should be declared as private and you should use getter and settle methods....
Meaning you will need to create a getter method in 'Cobject' to get the 'Bobject' object your after.... Then another getter/setter method to access any attributes there, or a method to manipulate any data
But yes, you could hard code a method that will go into the array and return what you ask for. Probably need an index parameter tho
you can create a getter method for Bobject[] in Cobject class
and then you can do c.getCObject1()[0].getBInstVar();

Is there any purpose to make private class variable to public

Hello I am curious to know that Is there any purpose to make private class variable to public in Java.
public class XYZ {
public String ID;
public ABC abc;
private class ABC {
public boolean isExist;
}
}
Thanks in advance.
Yes, there's a purpose. If you do that then those program elements which can access the class can manipulate that variable directly. Otherwise (say if the variable is private), those elements would still be able to access the class but won't be able to manipulate the variable (unless you provide a getter/setter for it).
Think about it this way: the class modifier defines the level of access to the class, the variable modifier then defines the level of access to the variable itself (for those elements which can access the class).
This is sometimes done for data-only classes. For example, this is sometimes done to represent the models stored in databases (see Objectify for a real example of how this is used, in conjunction with annotations, to represent the database models that are stored in an App Engine database).
That being said, this sort of thing makes for a very poor API. If you do this, I'd suggest doing it with classes that are either package-level access or in private nested classes, only. When exposing functionality or data to code outside your package, it is generally better to do it with a carefully designed interface that would allow you to change the implementation if your underlying structure were to change.
That is to make isExist visible to XYZ class.
Note, ABC is only visible to XYZ and not to any outside classes and its variable is public so you can have access to it. private has not meaning to XYZ, only outside classes
From inside XYZ,
ABC abc = new ABC(); //can only be accessed by XYZ.
abc.isExists = true; //can only be accessed by XYZ
Making isExist public means you do not care about encapsulating (prevent it from unwanted manipulation from outside) it. If you make it private, you will need a get accessor to expose it
private class ABC {
private boolean _isExist; //only through accessors
public boolean isExist()
{
return _isExist;
}
}
You can do either of the following two things to your class instance variables:
THING # 1: Keep your instance variables private. Then have public getter and setter methods to get and set the value of that variable. The good thing about it is that you get to put checks inside the setter method. For example, lengths can never be negative. So, you can't just make lengths public and let anyone assign it whatever value they want. You need to make sure the value being assigned to it is not negative. So:
class myClass {
private int length;
public void setLength(int i) {
if ( i > 0 ) {
length = i;
}
}
}
Also, you can make your instance variables read-only, write-only, or read-and-write, depending on the availability of getter and setter methods for that private variable.
THING # 2 : If you don't need any restrictions on the value of your instance variable, and you want it to neither be read-only nor write-only, then it's fine to keep that variable public. For example: babies can have any name - no restrictions:
class Baby {
public name;
}
class Mother {
public void nameTheBaby() {
Baby baby = new Baby();
baby.name = "Sarah";
}
}

Keeping track of all instances of a subclass in the superclass

I have the following, stripped-down Java code:
// Class, in it's own file
import java.util.*;
public class Superclass {
protected List<Subclass> instances = new ArrayList<>();
public class Subclass extends Superclass {
private int someField;
public Subclass(int someValue) {
this.someField = someValue;
updateSuperclass();
}
private void updateSuperclass() {
super.instances.add(this);
}
}
}
// Implementation, somewhere else, everything has been imported properly
Superclass big = new Superclass();
Subclass little1 = big.new Subclass(1);
Subclass little2 = big.new Subclass(2);
Subclass little3 = big.new Subclass(3);
I want to implement a method in Superclass to do something with all the Subclasses. When a Subclass is created, it should add itself to a list in Superclass, but whenever I try to loop through that list in Superclass, it says the size is 1. The first element in the list (instances.get(0)) just spits out a String with all the proper information, but not in object form, and not separately. It's like every time I go to add to the list, it gets appended to the first (or zeroeth) element in String form.
How can I solve this so I can maintain an ArrayList of Subclasses to later loop over and run methods from? I'm definitely a beginner at Java, which doesn't help my case.
If all you need is a count then I suggest a static value that is updated in the constructor of the parent class.
private static int instanceCount = 0;
public Constructor() {
instanceCount++;
}
If you absolutely need every instance in a list so you can do something with them then I recommend you strongly re-consider your design.
You can always create a utility class that will let you maintain the list of objects to run processes on. It's more "Object Oriented" that way. You can also create one class that has all of the operations and then a simpler bean class that has only the data values.
But, if you insist, you can still use the same technique.
private static List<SuperClass> list = new LinkedList<SuperClass>;
public Constructor() {
list.add(this)
}
Each instance gets its own copy of your superclass's variables.
What you want to do is make the variable "static" by putting the static keyword before it. You probably don't even need the superclass accomplish what you're trying to do.

Accesing a method from another class file?

I need to acces a variable (an int) from another class file. How would I do this? It's a public int, I need to get the int value and put it into a file.
If you have an instance:
AnotherClass another = new AnotherClass();
Then if the field (instance variable) is public:
another.someField;
or if you have a getter method
another.getSomeField();
If none of these is true - add a getter method (this is the preferred way to access instance variables).
If you can't change the class - as a last resort you can use reflection.
Example:
MyClass myclass = new MyClass();
System.out.print(myclass.myint)
Best practice code states that if the variable is not a Static Final, then you should create getters & setters inside the class:
public class Main{
int variableName;
public int getVariableName(){
return this.variableName;
}
public setVariableName(int variableName){
this.variableName = variableName;
}
}
If you want to acess it from another class file then you have to instantiate an Object and then access it using the public method:
Main m = new Main();
int a = m.getVariableName();
Hope it helps.
If you have an instance of that other class, you access it as {instance}.varable.
That varaiable need to either be public, or it needs to be in the same package and not private, or it must be a protected variable in a superclass.
If the variable is static, then you don't need an instance of that class, you would access it like {ClassName}.variable.
Far and away the best thing to do here would be to make the int you need to access a Property of the other class and then access it with a 'getter' method.
Basically, in the other class, do this:
public int Number
{
get
{
return number;
}
set
{
number = value;
}
}
private int number;
Doing this allows you to easily set that in to something else if you need to or to get it's current value. To do this, create an instance of the "AnotherClass" as Bozho already explained.

Categories

Resources