Java: how do I access the variables of another class - java

I have a class GameScreen which has an instance of a class Sprites (I have named the instance gameSprites). In Sprites there is an instance of a third class, which I have named enemies.
My question is, can I access a variable in enemies from GameScreen?
Can I type gameSprites.enemies.variableName?
And can I continue that for more than two different classes?

If Your Variable is Private you need to have Public method to access that Variable .
Suppose I have This Dummy Enemies Class of Yours
package com;
public class Enemies {
private final String name="HELLO";
public final String names="This is public Variable";
public static String name2="HELLO THIS IS STATIC";
public Enemies(){};
public String getName(){
return name;
}
}
and here in Sprites Class like your requirement i created Enemies instance
package com;
public class Sprites {
public Sprites(){};
Enemies enemies = new Enemies();
}
This is Dummy GameScreen Class
package com;
public class GameScreen {
public static void main(String...strings){
Sprites gameSprites = new Sprites();
System.out.println(gameSprites.enemies.names);
String name=gameSprites.enemies.name2;// This is Highly Discouraged Approach
System.out.println(name);
System.out.println(gameSprites.enemies.getName());
}
}
and the Output When You Run This Code.
This is public Variable
HELLO THIS IS STATIC
HELLO
So What you are trying to achieve can be done for public and Static variable(This one is not encouraged to do) . For private you need to have a Public Method to access that Variable.

In Java world, its not really recommended. You're able to access via objectName.memberName because your member attribute is a public one. As a convention, we usually keep members private and have getters and setter through which we access the values.
And coming back your question, you can access that way to any level given that each of the members are declared public. Say, gameSprites.enemies.enemy1.enemy1Army.solder1 is also possible if enemies is public in gameSprites class, enemy1 is public in enemies class and so on.

This is really very basic things of any OOP language. In my opinion, you should spend some times on study those basic things, otherwise there is a good chance that you will stuck further when you proceed from this problem. However, here is an example to how to access variable of other class from another class.
Accessing a variable from another class

It might be accessible if there is public property of class "enemies". But you are not doing it in a right way. You should make these properties private, then create public methods(getter/setter) to access the properties of those objects.

Related

Can objects of a class have access to its private methods?

I am a beginner with respect to programming in OOPS. I was going through the concept of access modifiers in a book and got stuck at a place:
The code is as follows(I didn't care about the syntax of the code as the doubt is a conceptual one):
public class Soldier{
private int health;
public int getHealth(){
return health;
}
public void setHealth(int newHealth){
health = newHealth;
}
}
class Hospital{
private void healSoldier(Soldier soldierToHeal){
int health = soldierToHeal.getHealth();
health = health + 10;
soldierToHeal.setHealth(health);
}
public static void main(){
Soldier mySoldier = new Soldier();
mySoldier.setHealth(100);
Hospital militaryHospital = new Hospital();
mySoldier.setHealth(10); //Soldier wounded
militaryHospital.healSoldier(mySoldier);//Soldier's health increased by 10
}
}
I had a doubt in the healSoldier(Soldier soldierToHeal) method. Since this method is private, it can be accessed only within the Hospital class according to what I understood regarding the private access modifier. But we are using the same method in main to heal the soldier. Is it possible for an object of a class to have an access to its private method from main?
Thanks in advance!!
The only reason this is allowed is that your main method belongs to the body of the same class - Soldier - that also contains the body of the Hospital class. This allows it to access all private members and methods of any instance of the Hospital class.
That said, if objects of the Hospital class are going to be used by other classes, and should be allowed to call healSoldier, you should make healSoldier public. And it makes little sense for the Hospital class to be an inner class of the Soldier class. It should be a top level class.
Is it possible for an object of a class to have an access to its
private method from main?
If the object is manipulated inside a method of this class, yes.
In this case it is able as the main(String[] args) method is a method of Hospital :
class Hospital {
private void healSoldier(Soldier soldierToHeal) {
int health = soldierToHeal.getHealth();
health = health + 10;
soldierToHeal.setHealth(health);
}
public static void main(String[] args) {
Soldier mySoldier = new Soldier();
mySoldier.setHealth(100);
Hospital militaryHospital = new Hospital();
mySoldier.setHealth(10); // Soldier wounded
militaryHospital.healSoldier(mySoldier);// Soldier's health increased by 10
}
}
I didn't care about the syntax of the code as the doubt is a
conceptual one)
The syntax matters.
You probably incorrectly entered the code of the class in your actual question as the main() method seems to be defined outside of any class.
private variables and methods can be accessed anywhere from the instance of the class that declares it.
In your case the healSoldier method is called via the object of class Hospital which has declared it.
"Since this method is private, it can be accessed only within the Hospital class according to what I understood regarding the private access modifier."
This is a wrong understanding.
The right understanding is:
"..., the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top-level type that encloses the declaration of the member or constructor."
see https://docs.oracle.com/javase/specs/jls/se11/html/jls-6.html#jls-6.6.1
https://docs.oracle.com/javase/specs/jls/se17/html/jls-6.html#jls-6.6.1

Problems with recognizing variables and methods from same package

I understand how to use and import outside packages, but I've never packaged my own classes before. I read the Oracle Tutorial on Creating a Package, and looked at In Java, what's the difference between public, default, protected and private in addition to several sites/SO threads on packages. For the life of me, I can't figure out why this extraordinary simple example doesn't work:
package PTest;
public class A
{
protected final int SIZE = 10;
public void printSize()
{
System.out.println(SIZE);
}
}
package PTest;
public class B
{
public static void main(String[] args)
{
System.out.println(SIZE);
hello();
}
}
I used eclipse's autopackaging feature, so I assume that the actual packing is correct. Here's an image to show that they are indeed packaged correctly:
As you can see, neither the protected SIZE or the public hello() are recognized. I've tried this outside of eclipse, also to no avail. Any help would be greatly appreciated.
SIZE is an instance field of A objects. You need to make it a static field. Even then, it'll be a member of the A class, so you have to specify A.SIZE to use it in B.
Class methods cannot access instance variables or instance methods directly—they must use an object reference.
Errors you getting are fixed here
package PTest;
public class B
{
public static void main(String[] args)
{
A MyClassA = new A();
System.out.println(MyClassA.SIZE);
MyClassA.printSize();
}
}
You can not directly access methods or fields which are not static (instance members) being in a static scope(main) other than using an object and then access or making those instance members as staic.(class members)

How to create a class with a package private constructor?

I'm working on a library where I want to return an object representing a real world object. I want to expose this class to developers to manipulate the real world object, but I don't want to allow them to construct these objects themselves.
Example
public class World {
public static List<RealObject> getAllObjects() {
// How to create RealObject with physicalID?
}
}
public class RealObject {
private int physicalID;
public RealObject(int physicalID) {
// Undesirable, user has no knowledge of IDs
}
public void setState(int state) {
// Code using physicalID to change state
}
}
These objects currently have no constructor and have a private id field that I set with reflection from within my library. This works perfectly, but I can't help but think there must be a better solution. Perhaps a useful constraint in my situation is that it only needs to be possible to construct this object from one other class.
Is there a better solution? And is it still possible to have the class in a separate file in that case for organizational purposes?
If you put default access level on constructor (or any other method), then can be accessed only by classes from same package.
To concretely answer the question in the title:
public class RealObject {
RealObject(int physicalID) {
// Package-private constructor
}
}

Java - Declare Class Once Use Anywhere

Very simple problem but im not understanding static correctly.
I have java file which holds my main and its call testMain.
With my testMain it makes many classes with use other classes.
E.g. testMain>>GUI and testMain>>model and testMain>>controller
Now i have a class called generatorTester which i would like to declare once like:
public static utils.generatorTester randomGen = new utils.generatorTester ();
(utils is my custom package for my common classes)
Why does the above line not aloud me to do the following
classNameOfMainFunction.randomGen
Im i programming wrong here? Is this even possbile.
I bassicly want to make the class globably and use it any where.
A public static field of a public class can be used anywhere, you just need to use the right syntax to access it.
If you declare:
package foo;
public class Global {
public static Some thing;
}
And do
import foo.Global;
you can access the field with
Global.thing
Alternatively, you can do
import static foo.Global.thing;
and access it with
thing
About the best you can get is this:
public abstract class GloballyUsed {
public static int method() { return 4;
/* determined by fair
* dice roll, guaranteed to be random */
}
and:
GloballyUsed.method();
to call elsewhere.
Note per comment (I just learned this) since Java 5 you can import just a specific method name as:
import static {package}.GloballyUsed.method;
Note I added the keyword abstract, this is to further convince you that you never actually instantiate GloballyUsed. It has no instances. You probably have some reading to do on what static means.

jMockit's access to a private class

I have a public class with a private class inside it:
public class Out
{
private class In
{
public String afterLogic;
public In(String parameter)
{
this.afterLogic = parameter+"!";
}
}
}
And wanted to test the In class with jMockit. Something along these lines:
#Test
public void OutInTest()
{
Out outer = new Out();
Object ob = Deencapsulation.newInnerInstance("In", outer); //LINE X
}
The problema is, in LINE X, when trying to cast ob to In, the In class is not recognized.
Any idea how to solve this?
Thanks!
The only constructor in class In takes a String argument. Therefore, you need to pass the argument value:
Object ob = Deencapsulation.newInnerInstance("In", outer, "test");
As suggested in the comment one way is to change the access modifier of the inner class from private to public.
Second way (in case you don't want to make your inner class public), you can test the public method of outer class which is actually calling the inner class methods.
Change the scope of the inner class to default then make sure that the test is in the same package.
There are two approaches, first as mentioned in other posts to change the scope to public. The second which I support is, to avoid testing private class altogether. Since the tests should be written against testable code or methods of the class and not against default behavior.

Categories