Reputation: 11
i'm a novice in java and i don't know how to call a variable from a private class to another. Currently i'm using NetBeans 8.1 and here's the class from which i wanna take the values
public class Mars {
public static String name;
private static int fuel;
private static int AI;
private static int tecnology;
public void setName(String nm)
{
name = nm;
}
public void setFuel(int fl)
{
fuel = fl;
}
public void setAI(int ai)
{
AI = ai;
}
public void setTecnology(int tc)
{
tecnology = tc;
}
public String getName()
{
return name;
}
public int getFuel()
{
return fuel;
}
public int getAI()
{
return AI;
}
public int getTecnology()
{
return tecnology;
}
private static class name {
public name(){
name = "unknown";
}
}
private static class fuel{
public fuel() {
fuel = 50;
if ((fuel >100) || (fuel <0))
{System.out.println("\nError!");
System.exit(0);}}}
private static class AI {
public AI() {
AI = 5;
if ((AI >10) || (AI <1))
{System.out.println("\nError!");
System.exit(0);}}}
private static class tecnologiy {
public tecnologiy() {
tecnology = 5;
if ((tecnology >10) || (tecnology <1))
{System.out.println("\nError");
System.exit(0);}}}
}
And here is the class where i want to put the values:
public class Space_Battle {
public static void main(String[] args) {
Mars Call1 = new Mars();
System.out.println("\nThe alien named " + Mars.name + " joined the battle" );
}
}
Naturally every correction will be very appreciate! :-D P.S. I'm sorry if this question is ridicoulos.
Upvotes: 0
Views: 148
Reputation: 146
You cant directly set values to private variables from another class, thats why they are private.
You HAVE to instantiate an object of the said class.
Example:
Mars call1= new Mars();
then you can set values to that object.
call1.setName("whatever");
then to get the value of the object just use the getter.
call1.getName();
then to print it:
System.out.println("\nThe alien named " + call1.getName() + " joined the battle" );
Also, remove the static from your variables.
I would also encourage you to read about the "this" keyword.
I recommend you to read this documentation: https://docs.oracle.com/javase/tutorial/java/concepts/object.html
Upvotes: 0
Reputation: 6503
Change your code to this...
public class Space_Battle {
public static void main(String[] args) {
Mars mars = new Mars();
System.out.println("\nThe alien named " + mars.getName() + " joined the battle");
}
When you create an instance of an object, you should access it via secure accessors i.e. getter methods, getName(), etc.
And remove the static declaration from your private variables.
Upvotes: 1