Creating and passing objects java - java

Trying to understand how to correctly access and pass other objects within a program using java.
In my little program we see the following:
I have a combat class that will need to know the current HP of my hero, which is an instance of my Hero class.
Previously, if another class needed to know the hero's HP, I would simply use a static variable to store HP. I was told this was incorrect usage of static. Below, I created a method in combat for the explicit use of passing the hero into combat. Thus, going forward, any time I need combat to access anything related to my hero object, I can.
Does this make sense? Am I on the right path?
public class Combat
{
public void passHero(Hero hero1)
{
}
}
public class Main
{
public static void main(String args[])
{
Hero hero1 = new Hero();
//passing hero to Combat
combat.passHero(hero1);
}
}

You are on the right track. When you want to set attributes on an object (in this case the Hero attribute of Combat), that object (Combat) usually provides public methods for setting and retrieving its attributes. You probably want to just create a hero setter on the combat class, or pass the hero in to a constructor
public class Combat
{
private Hero hero;
//setter
public void setHero(Hero hero1)
{
this.hero = hero1;
}
//constructor
public Combat(Hero hero1)
{
this.hero = hero1;
}
}
public class Main
{
public static void main(String args[])
{
Hero hero1 = new Hero();
//passing hero to Combat
Combat combat = new Combat(hero1);
//or
combat.setHero(hero1);
}
}

Related

How can I use non static variable(object ref) in static method without creating object inside that static method in java?is there any way to do it?

I'm new to Java. I get this error when running the code below
Cannot make a static reference to the non-static field universityObj
But not getting error while using
University universityObj = new University();
The code:
public class University {
String name;
int stuno;
String university_name = "Michigan University";
University universityObj;
public static void main(String[] args)
{
University universityObj = new University();
universityObj.name="Robert";
universityObj.stuno=12;
System.out.println(universityObj.name);
System.out.println(University.university_name);
display();
}
public void nonStaticDisplay()
{
System.out.println(name);
System.out.println(stuno);
}
public static void display()
{
universityObj = new University();
System.out.println(universityObj.name);
}
}
Let's go step by step.
The display() method should be non-static because it belongs to and should be used on the specific instance of the University class. Static methods can be used without creating an instance of some class. But in the case of the display() method, it wouldn't makes sense to do that because you need to display the university name, which firstly should be created and assigned.
It's not a good idea to create the object instance University universityObj inside the class in your case. Better to leave it only in the main method.
The university_name name is not static, so you can't access it without the class instance (object) like you're doing right now. University.university_name should be changed to universityObj.university_name.
These steps will bring us to a such piece of code:
public class University {
String name;
int stuno;
String university_name = "Michigan University";
public static void main(String[] args) {
University universityObj = new University();
universityObj.name = "Robert";
universityObj.stuno = 12;
System.out.println(universityObj.name);
System.out.println(universityObj.university_name);
universityObj.display();
}
public void display() {
System.out.println(name);
System.out.println(stuno);
}
}
Other things, which you should consider:
Read about encapsulation.
Use code formatting in your IDE. Example for IntelliJ IDEA.
Check the toString() method from the Object class. It's intended exactly for what you're trying to achieve with your display() method.
You might simply pass a reference to the instance you want to be displayed. Like,
public static void display(University universityObj)
{
System.out.println(universityObj.name);
}

Why can I not access an instance of class that is created in a constructor ( Java )

To preface the question, I'm very new to Java.
I have classes called, Game, Player, and SystemIO.
My main() is in the Game class. Below is it's code
public static void main(String[] args){
SystemIO systemIO = new SystemIO();
}
Once SystemIO is called, it's constructor creates an instance of Player with the line
Player player = new Player("Bob");
where the Player constructor takes 1 argument as a String.
Further down in the SystemIO class I have a method that accesses information from "player" the instance.
player.getName();
When I try to do this, the console reports
SystemIO.java:339: error: cannot find symbol
I have checked that I am not trying to reference the class name with a capital "Player."
Like I said, I'm extremely new to Java and just trying to wrap my head around it and I believe it's a scope issue...but I'm not sure.
Edit to add reproducible code:
Game.java
package com.myapps;
import com.myapps.system.SystemIO;
public class Game{
public static void main(String[] args){
SystemIO systemIO = new SystemIO();
}
}
Player.java
package com.myapps.player;
public class Player{
String name;
public Player(String playerName){
name = playerName;
}
}
public String getName(){
return name;
}
SystemIO.java
package com.myapps.system;
import com.myapps.player.Player;
public class SystemIO{
public SystemIO(){
Player player = new Player("Bob");
readPlayerName();
}
public void readPlayerName(){
System.out.println(player.getName());
}
}
Make player a class variable.
Put someone in your class:
Player player;
and change the code of your constructor to:
player = new Player("Bob");
This is called a scope error. A variable that you want to be accessable to ALL the methods of the class, should be declared IN the class and not in ONE specific method (in your case, you did it in the constructor)

How do you pass an updated global class variable from one method into another?

I update a variable (which is global in the class) in one method and I cannot seem to be able to then pass that updated variable into another method.
Any help would be appreciated, thank you.
Here's my shortened code:
public class Game{
private int randomIndexX;
protected String spawn(){
randomIndexX = randomGenerator.nextInt(10);
return null;
}
protected String test(){
System.out.println(this.randomIndexX);
return null;
}
}
public class Player extends Game{
protected String getNextAction(String command) {
switch(command){
case "test":
test();
break;
}
}
}
public static void main(String[] args) {
Game game = new Game();
Player player = new Player();
game.spawn();
player.getInputFromConsole();
}
EDIT: so when i call test() from the Player class i want it to print out randomIndexX but it still doesn't seem to be working even with this.randomIndexX in the method test()
EDIT: so when i call test() from the Player class i want it to print out randomIndexX but it still doesn't seem to be working even with this.randomIndexX in the method test().
So test() is instance method, which means you'll have to make an instance of Class Game in order to call that method, your randomIndexX is instance member so you need to think well what you want to do, IF randomIndexX is common for all the objects of Game class, you should declare it static as in:
private static in randomIndexX;
As it's value won't change depending on an object instance.
So in order to access that variable from outside of the class since it's private you declare a public method to retrieve that value (getter or also known as accessor):
public static int getRandomIndex(){
return randomIndexX;
}
So when in main, you don't even have to make an instance of the Game class to access value that's being held in randomIndexX, you just call the getter method like this:
System.out.println(Game.getRandomIndex());
The line above will print 0 to the console as 0 is default value for members of type int, now if you want to be able to change it, you just make a setter or mutator method in Game class as well:
public static void setRandomIndex(int n){
randomIndexX = n;
}
And there you go, you can now set and retrieve "randomIndexX" field from outside of the Game class.
For example, the code below will set value of randomIndexX to 5 and then print it in the console:
Game.setRandomIndex(5);
System.out.println(Game.getRandomIndex());
The first problem I can see is that you don't have a constructor.(Optional)
(If you don't make one the compiler makes what is called a "Default" constructor which is a constructor without any parameters. Its usually good practice to explicitly create a class constructor.
The second problem I can see is that you missing the end bracket.
Fix shown below.
public class Game
{
private int randomIndexX;
protected String spawn()
{
randomIndexX = 0;
return null;
}
protected String test()
{
System.out.println(randomIndexX);
return null;
}
}
You can construct it and trigger any methods you wish:
Game game = new Game();
game.spawn();
game.test()

How to access an object from a different class and package?

So, I am a learning programmer and I started to learn Java 2 months ago as a course at my university. I really like to program in my spare time and I'm currently trying to make a game. There is one problem at the moment which I just can't solve.
I have a class called Move, and I declare in my class called Start:
Move move1 = new Move();
Now when I'm back in my Move class, I would like to access this move1 but it doesn't let me. It says:classname cannot be resolved.
To clarify:
public class Move {
private String s = null;
public void setName(String s) {
name = s;
}
public String getName() {
return name;
}
public void setList() {
System.out.println(move1.getName() + move2.getName()); // This won't work
}
}
And the start class:
public class Start {
public static void main(String[] args) {
Move move1 = new Move();
Move move2 = new Move();
move1.setName(kick);
move2.setName(punch);
}
}
It would be awesome if someone could help me out!
-edit
OK! I got a few reactions but I didn't really get the answer I need. I know now i can use this instead of the object name but what if I want to use a second object? I changed code the above.
The problem you have is that the names move1 and move2 are out of scope in the setList method. They're defined in Start.main as local variables, so they are only visible there.
There are a innumerable ways you can solve this. The most straight-forward way is to move the setList method to Start. Because you're calling it from main, which is a static method, setList will also have to be static.
public class Start {
public static void main(String[] args) {
Move move1 = new Move();
Move move2 = new Move();
move1.setName(kick);
move2.setName(punch);
setList(move1, move2);
}
public static void setList(Move move1, Move move2) {
System.out.println(move1.getName() + move2.getName());
}
}
If you think setList should be in the Move class, you'll need to pass the second move as a parameter.
public class Move {
...
public void setList(Move other) {
System.out.println(this.getName() + other.getName());
}
}
You don't need to say move1.getName(). You can say this.getName() instead. The keyword this refers to whatever object is calling the method - in this case, move1.
This is because the object move1 only exists in the scope of the main method in Start. Therefore, "move1" is meaningless anywhere other than main.
In reality, the keyword this can be omitted; you could just say getName() without putting anything in front of it.
move1 is the object of Move class define in the Start class so you cant access it.You can simply access the method of Move class with below line.
System.out.println(getName()); // THis will work
The correct way to access current move object (move1) is using this key word. You could say System.out.println(this.getName()); in Move class.
Maybe you didn't add import of class Move? It necessary when you access an object from a different package.

How can I access a Local Variable which is an object from within another class? - Java

My understanding is that you can't do what I'm asking. If you look at the starred (*) commented errors in the code below, you can see what I'm trying to access. I feel like I need to be able to do this so that I can use a method to dynamically create many objects and then access all of those objects from other objects.
Is there a way to do this that I'm missing, or am I just messing something up? If not, how should I go about doing this to enable me to get the same functionality as below? If there's any way to do this other than passing the objects around, it would be appreciated (passing objects seems like so much work - especially with multi-dimensional arrays of objects - there should be an easy way to instantiate package-private objects that can be accessed anywhere else in the package). But if passing is the only way, please let me know the best way to do it, especially when I'm passing a two-dimensional array of a bunch of objects. Thanks!
package simpleclasswithinclasstest;
class Game {
static int boardSize;
Engine gameEngine;
Game() {
}
public void run() {
gameEngine = new Engine();
gameEngine.play();
}
public int getBoardSize() {
return boardSize;
}
}
class Engine {
int boardSize;
Engine() {
}
public void play() {
this.boardSize = currentGame.getBoardSize(); // *****1 Error is here.
// *****It doesn't recognize currentGame, but I want it to.
}
void doNothing() {
}
}
class Board {
Board() {
}
void Test() {
gameEngine.doNothing(); // 2 *****Error is here.
// *****It doesn't recognize gameEngine.
}
}
public class SimpleClassWithinClassTest {
static Game currentGame;
public static void main(String[] args) {
currentGame = new Game();
currentGame.run();
}
}
You will get access to gameEngine through your Board class by passing it as a parameter to Board. When you instantiate your Board, you could do something like this:
class Engine {
int boardSize;
Engine () {
Board board = new Board(this);
}
public void play() {
}
void doNothing() {
// magic stuff in here
}
}
class Board {
Engine engine;
Board (Engine gameEngine) {
this.engine = gameEngine
}
void Test() {
engine.doNothing(); // No error here :-) and this engine is your main one
}
}
Take a look at the concept of message-driven communication. Things might get clearer for you by reading this answer.
In the following picture, which I took from the answer linked above, you can imagine f as your engine object within the Engine class, and c as your engine within the Board class. You are actually manipulating the same object.
As for your other problem (the first one): it can't recognize currentGame because you don't have any variable with that name in your scope.
There is no variable of any type named 'currentGame' in scope at that point in the code.
Furthermore, while boardSize is a static package-protected variable, the method getBoardSize() is an instance variable. One possible solution is to make the method static and package protected, then you can do this:
public void play() {
this.boardSize = Game.getBoardSize();
}
This is like initializing an int variable in 1 function and trying to access it from another function.The objects(you are trying to access) are out of scope in the part of the code where you are trying to access.You can resolve this issue by sending this
as a parameter and recieving it as an object in the corresponding method.
We can use class reference to call static methods only. So you can make the play a static method.
class Engine {
int boardSize;
Engine() {
}
public void play() {
this.boardSize = currentGame.getBoardSize(); // *****1 Error is here.
// *****It doesn't recognize currentGame, but I want it to.
}
static void doNothing() {
}
}
class Board {
Board() {
}
void Test() {
Engine.doNothing();
}
}
The other way is to make an Object from the class and access the non static methods within that object.
class Engine {
int boardSize;
Engine() {
}
public void play() {
this.boardSize = currentGame.getBoardSize(); // *****1 Error is here.
// *****It doesn't recognize currentGame, but I want it to.
}
void doNothing() {
}
}
class Board {
Board() {
}
void Test() {
Engine gameEngine = new Engine();
gameEngine.doNothing();
}
}

Categories

Resources