Answer the question
In order to leave comments, you need to log in
newbie! Java classes and objects, correct class layout and invocation
I recently started learning OOP and Java. A pack of noob questions :)
We have a Main class in which the main program is processed, and two sub-classes Player / Location
Player class stores information, say, about players and their characteristics. As I understand correctly, first we set variables and default values for the class.
Player.java
public class Player {
public String characterName = "N/A";
public String characterClass = "Paladin";
public String characterSex = "Man";
public int characterPlayedTime = 0;
public int characterLevel = 1;
public int characterDamage = 100;
}
public class Player {
public String characterName = "N/A";
public String characterClass = "Paladin";
public String characterSex = "Man";
public int characterPlayedTime = 0;
public int characterLevel = 1;
public int characterDamage = 100;
public Player adept = new Player {
public String characterName = "Adept";
public String characterClass = "Rogue";
public String characterSex = "Man";
public int characterPlayedTime = 15;
public int characterLevel = 30;
public int characterDamage = 500;
}
}
Answer the question
In order to leave comments, you need to log in
Sometimes it is required to create an object of a certain class with preset values, or to return some (I call them global) previously created object.
The first possibility is implemented in the class constructor:
public class Player {
public String characterName = "N/A";
public String characterClass = "Paladin";
public String characterSex = "Man";
public int characterPlayedTime = 0;
public int characterLevel = 1;
public int characterDamage = 100;
public Player () {
characterName = "Adept";
characterClass = "Rogue";
characterSex = "Man";
characterPlayedTime = 15;
characterLevel = 30;
characterDamage = 500;
}
}
... will create in each created new object the values previously written in the constructor. Once created, they can be changed to others. public class Player {
public String characterName = "N/A";
public String characterClass = "Paladin";
public String characterSex = "Man";
public int characterPlayedTime = 0;
public int characterLevel = 1;
public int characterDamage = 100;
public static Player adept() {
Player ret = new Player();
ret.characterName = "Adept";
ret.characterClass = "Rogue";
ret.characterSex = "Man";
ret.characterPlayedTime = 15;
ret.characterLevel = 30;
ret.characterDamage = 500;
return ret;
}
}
... a static function will return the object created in it, having previously assigned the necessary values to the object's fields. They can also be changed.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question