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

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.

Related

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()

Questions about Java upcasting/downcasting and inheritance pripority

Having trouble understanding the intricaies of upcasting/downcasting, and static binding and dynamic bidning in these cases. Please consider the following classes and interface example:
public class Marsupial { private String name;
Marsupial(String name) {
this.name = name;
}
void eats() {
System.out.println("Eats #1");
}
String getName(){ return name;
}
}
abstract class Herbivore extends Marsupial {
Herbivore(String name) {
super(name);
}
void eats() {
System.out.println("Eats #2");
}
abstract void chews(boolean b);
}
interface Australian {
public void greets(Koala k);
}
public class Koala extends Herbivore implements Australian {
Koala(String name) {
super(name);
}
public void greets(Koala k) {
System.out.println("G'day mate!");
System.out.println(getName() + " " + k.getName() );
}
void chews(boolean b) {
System.out.println("Yum yum!");
}
void chews(int i) { System.out.println("Delicious!");
}
void likes(Koala k) {
greets(k);
k.greets(this); }
}
Now when I make a driver class to use all of the classes I notice some odd things happening that I am not sure why.
For example,
public class Driver {
public static void main(String[] args) {
Marsupial m = new Marsupial("Kate");
Marsupial m2 = new Koala("Kim");
System.out.println(m.getClass() == m2.getClass());
}
}
This turns out to be false. They are not the same class. So what is happening here exactly. We have Marsupial on the left and something else on the right. So does what's on the right the only thing that matters when we are calling methods? When the compiler runs and looks at methods does is check the right side of the equals operator and say ok this is such and such class, therefore use the methods of the class defined on the right side when figuring out whose class to use.
Also,
if inside the main method I wrote:
Marsupial m = new Koala("jack");
m.eats();
This prints out Eats #2. Now is this because since Koala does not have a eats method is just goes back one level up the chain, so the next level up would be Herbivore and since that has an eats() method that is what gets called, is that the idea there?
Another example in the main method:
Herbivore h = new Koala("June");
((Marsupial)h).eats();
Here the thing that throws me off is that we can use abstract classes as a reference to actual objects, like here Herbivore is an abstract class therefore cannot be instaniated, but it can be assigned to a class that does instantiate an object.
But what confuses me most is that now we are in the Koala class and we call the eats() method but then we UPCAST the variable to Marsupial. So does that automatically put us in the Marsupial class and therefore anytime we call a method even if its in other classes the Marsupial class method is the one that gets called since we typecasted it to Marsupial, therefore its Eats #1.
Another area of confusion is if we do this in main:
Australian a = new Koala("Khloe");
a.chews(true);
It's werid seeing an interface be assigned to a subclass instantiation. It confuses me what would get called with a.chews(true). So since it's been defined as a Koala object then we are IN the Koala class and must use Koala methods if they exist, and if not there we go one level up to check that they have that method and so on and so fourth. But here the method is invalid. So does it only work if Australian had a prototype method in there and Koala defined it? then it would work? Is that the idea behind setting interfaces as objects of their subclasses? Even though Koala has that method since Australian does not, it will not work.
And if we have the code in main like:
Herbivore h = new Koala("Stacy");
h.chews(true);
this will print out "Yum yum" only because Herbivore had that prototyped undefined method and Koala defined it. But if Herbivore didn't have that prototype method is wouldn't work.
The last question I have is if this were run in main:
Herbivore h = new Koala("Kali");
h.chews(4);
This won't work because despite the fact that Koala has this method in there, it's not defined in Herbivore, so it's invalid.
Please help, any corretions or information you could provide would be very helpful.
Thank you
The answer to all is one: as far as
the JVM is concerned it doesn't
care one bit about the variable
type, but only the actual type (the
one used with the new keyword)
. Variable types are for the
compiler only to ensure type
safety as early in development
possible.

How to use a variable in two classes?

I need to be able to see in all of these classes if the variable is true.
public void performAction() {
if (door.intersects(HERO)) {
System.out.println("ActionPerformed!");
HeroX = 0;
HeroY = 0;
inside = true;
}
}
This is every time I press SPACE and now I want to draw the inside of the House.
In the Main class where I draw everything I want to say something like:
public void paintComponent(Graphics g) {
if (!inside) {
g.drawImage(Background, 0, 0, null);
achilles.Draw(g);
}else if (inside) {
g.drawImage(HouseInside, 0, 0, null);
}
}
I don't know how to change the "inside" in the Hero class and use it in the Main class. I have tried so many things and I don't know what to do.
inside is a property of a HERO object, so, if the property is public, you can access it with heroname.inside
If the property is private (which it generally should be), you have to use a public access function inside the HERO class, such as HERO.isInside, and set it with a setting function like HERO.setInside and HERO.setOutside.
this is often called "getters and setters"
What you probably want are global variables
public class Global{
public static int value;
}
You can then access them from anywhere:
Global.value;
If you Main class has a reference to all instances of the Hero class, then the usual best practice would be for the Hero class to expose a method like this:
public boolean isInside () {
return (inside);
}
If there is only ever one instance of the Hero class (unlikely, but ok), then one option is to make inside a public static variable like this:
public static boolean inside;
referenced from Main like this:
if (! Hero.inside) {
or make inside a private static variable with a getter like this:
private static boolean inside;
public static boolean isInside () {
return (inside);
}
referenced from Main like this:
if (! Hero.isInside ()) {
Try using a getter to get the inside attribute outside of Hero, and a setter to change it:
public class Hero {
private boolean inside;
...
public boolean isInside() {
return this.inside;
}
public void setInside(boolean inside) {
this.inside = inside;
}
}
I'd also recommend reading more about encapsulation; it'll give you a better idea about how to work with objects in Java.
You could model it differently:
public class House {
Location currentLocation=Location.OUTSIDE;
Map<Location, String> layout=new HashMap<>();
public House(){
layout.put(Location.INSIDE,"Draw the inner parts");
layout.put(Location.INSIDE,"Draw the outer parts");
}
public void enterDoor(){
currentLocation=(currentLocation==Location.OUTSIDE)?Location.INSIDE:Location.OUTSIDE;
}
public void draw(){
System.out.println(layout.get(currentLocation));
}
}
Here enterDoor is something, which could be fired by an event in your game-environment. So your House knows how to draw itself depending on its state.
Say your character moves to some coordinates (x|y), where the door is, the enterDooris called upon House, which in turn switches the layout.

<T> cannot be resolved to a type Java

I've got three classes:
One class which handles my main game operations. Its name is 'PlatformerGame'.
Note: Removed all game-related stuff.
public class PlatformerGame {
public PlatformerGame()
{
}
}
Then, I've got a class called 'PlatformerSingleton' which is meant to provide exactly one instance of the PlatformerGame.
public class PlatformerSingleton {
private static PlatformerGame game;
protected PlatformerSingleton()
{}
public static PlatformerGame getGame()
{
if (game == null)
game = new PlatformerGame();
return game;
}
}
And lastly, I've got the entry point of my application which is supposed to do nothing but get the instance of PlatformerGame and call its 'start' method.
public class Entry {
public static void main(String[] args) {
new PlatformerSingleton.getGame().start();
}
}
However, this is where the error happens:
What does this error mean and how can I prevent it? Also, are there any better approaches to implement this?
Note: I require access to the singleton instance from multiple classes, therefore I need this singleton class.
Don't add new in the line new PlatformerSingleton.getGame().start();
just change your line to:
PlatformerSingleton.getGame().start();
you are not creating new object here, you are just calling the static method of PlatformerSingleton class in which the object of the class is created using Singleton Design Pattern
Remove the new in that call:
new PlatformerSingleton.getGame().start();
Currently, it looks like you're trying to instantiate a class called PlatformerSingleton.getGame (a static nested class called getGame inside PlatformerSingleton).
You're looking for the static method inside PlatformerSingleton. Since it's static, you don't want to instantiate using new at all.
The compiler sees that the syntax is correct, but it doesn't find such class and thus throws an error. These kinds of errors are a bit tougher to correctly debug (as the actual error is syntactical), so you need to look a bit farther to fix it.
Just remove the newkeyword (you don't need new because you're creating PlatformerGameinstance inside of the getGame method):
public static void main(String[] args) {
PlatformerSingleton.getGame().start();
}
Since getGame() is a static method, you do not need to use the new keyword to call the method.
public static void main(String[] args) {
PlatformerSingleton.getGame().start(); // new keyword is not required
}
If getGame() was not static, only then it would have required an instance of PlatformerSingleton class for it to be called and that would have looked like
public static void main(String[] args) {
new PlatformerSingleton().getGame().start(); // if getGame() was a non-static method
}

invoking method in main method in Java

I have a question regarding to using method in main class, here is my code for a Race class:
import java.util.ArrayList;
public class Race {
private ArrayList<Car>cars;
public Race(){
cars = new ArrayList<Car>();
}
public void addCars(Car car){
cars.add(car);
}
}
The above is what I have done to make an arraylist for the cars that I am ready to put in by using a main method in another class:
public class Test {
public static void main(String[] args) {
Car toyota = new Car("Toyota",1.0,1.0,2.0,2.0);
cars.addCars(toyota);
}
}
However, it has error in the last line, it shows "cars cannot be resolved",I am not sure how should I fix it, maybe writing a getter method in the Race class?
Create an instance of race and call addCars
Race race = new Race();
race.addCars(toyota);
cars does not exist in that context, you might want to stick to the convention on having lowercase variable names, as well.
Change your Test class to something similar to this:
public class Test {
public static void main(String[] args) {
Race race = new Race();
Car toyota=new Car("Toyota",1.0,1.0,2.0,2.0);
race.addCars(toyota);
}
}
You want to add cars to the race, not cars (which does not exist).
To add cars to a race, you first need to make one.
By adding cars to the race, it will internally add it to the cars list. (Because you made it so)
You problem is basically that you are trying to use a variable that is outside the scope. (Somewhere else, basically)
Since I don't know your exact problem, I can't really help you further, but you might want to save the race in a field rather than a local variable, it all depends on what you want to do.

Categories

Resources