Okay, I can't figure out how to work this. When the object isn't static, none of the methods or variables used work, Java just won't compile them. However, when I make the object static, the JVM returns error, throwing a popup alert and spamming the console with error messages. Here's a severely cut down version of the broken code:
public class Main {
public Hero hero = new Hero();
private static boolean newGuy;
public static void main(String[] args){
areYouNew();
if(newGuy){
createGame();
}else{
loadGame();
}
saveGame();
}
private static void createGame() {
}
private static void loadGame() {
System.out.println("Ah yes, sorry. What is your name again?");
//blah blah code here
hero.setName();
if(hero.getName().length() > 0 ){
}else{
System.out.println("Sorry? You need to type your name");
loadGame();
}
}
private static void areYouNew() {
System.out.println("Are you new?");
String newTest = sc.nextLine();
if(newTest.toLowerCase().contains("yes")){
newGuy = true;
}else if(newTest.toLowerCase().contains("no")){
newGuy = false;
}else{
System.out.println("Oops, it's a yes or no question.");
areYouNew();
}
}
}
None of the hero.whatevers work unless I set hero to static. Any way to fix this?
I already tried making the methods containing the references to hero non-static but then I can't use those methods in main()
The static part of a program is code that runs without using an instance of your Main class. When the main method is called, there is no instance of the Main class yet.
Normally, an object instance has certain fields. In your case there is only public Hero hero. Static fields, like private boolean newGuy are not part of the instance, but more like global variables. Since there is no object instance of Main yet, the hero field can't be accessed.
It is good practice to use object-oriented programming, in Java. You should probably create a new instance of your game as quickly as possible (using Main game = new Main()). Then call methods on this instance (game.createGame(), game.loadGame()). Then, you don't need to make these methods static and you can access non-static fields. Also, this would allow you to have two Main instances at the same time, each with their own hero field, if such a thing would be needed at some point in your project.
You could, of course, also make the hero field static. It's a question of code style, I suppose.
Related
I was facing an error before, but when I made an object in this class the and called for the method, it worked flawlessly. Any explanation? Do I always have to make an object to call for methods outside of the main method (but in the same class)?
here:
public class A{
public static void main(String[] args){
A myObj= new A();
System.out.println(myObj.lets(2));
}
public int lets(int x){
return x;
}
}
You need to understand static. It associates a method or field to the class itself (instead of a particular instance of a class). When the program starts executing the JVM doesn't instantiate an instance of A before calling main (because main is static and because there are no particular instances of A to use); this makes it a global and an entry point. To invoke lets you would need an A (as you found), or to make it static (and you could also limit its' visibility) in turn
private static int lets(int x) {
return x;
}
And then
System.out.println(lets(2));
is sufficient. We could also make it generic like
private static <T> T lets(T x) {
return x;
}
and then invoke it with any type (although the type must still override toString() for the result to be particularly useful when used with System.out.println).
There are a importance concept to consider an is static concept. In your example you have to create an instance of your class because the main method is static and it only "operate" with other statics methods or variable. Remember that when you instantiate a class you are creating a copy of that class an storing that copy in the instance variable, so as the copy (That was create inside of a static method in your case) is also static so it can access the method which is not static in that context.
In order to not create an instance and access to your method you need to make your lets method static(due to the explanation abode)
public static int lets(int x){
return x;
}
And in your main you don't need to instantiate the class to access to this method.
public static void main(String[] args){
System.out.println(lets(2));
}
Check this guide about static in java: https://www.baeldung.com/java-static
Hope this help!
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
If I understand the meaning of each keyword correctly, public means the method is accessible by anybody(instances of the class, direct call of the method, etc), while static means that the method can only be accessed inside the class(not even the instances of the class). That said, the public keyword is no use in this situation as the method can only be used inside the class. I wrote a little program to test it out and I got no errors or warnings without putting the public key word in front of the method. Can anyone please explain why public static methods are sometimes use? (e.g. public static void main(String[] args))
Thank you in advance!
Static methods mean you do not need to instantiate the class to call the method, it does't mean you cannot call it from anywhere you want in the application.
Others have already explained the right meaning of static.
Can anyone please explain why public static methods are sometimes use?
Maybe the most famous example is the public static void main method - the standard entry point for java programs.
It is public because it needs to be called from the outside world.
It is static because it won't make sanse to start a program from an object instance.
Another good examle is a utility class, one that only holds static methods for use of other classes. It dosen't need to be instantiated (sometimes it even can't), but rather supply a bounch of "static" routines to perform, routines that does not depend on a state of an object. The output is a direct function of the input (ofcourse, it might also be subject to other global state from outside). this is actually why it is called static.
That said, the static keyword is not always used because you want to have access to some members in a class without instantiating it, but rather because it makes sense. You keep a property that is shared among all instances in one place, instead of holding copies of it in each instance.
That leads to a third common use of public static (or even public static final) - the definition of constants.
A public static method is a method that does not need an instance of the class to run and can be run from anywhere. Typically it is used for some utility function that does not use the member variables of a class and is self contained in its logic.
The code below chooses a path to store an image based on the image file name so that the many images are stored in a tree of small folders.
public static String getImagePathString(String key){
String res = key.substring(3, 4)+File.separator+
key.substring(2, 3)+File.separator+
key.substring(1, 2)+File.separator+
key.substring(0, 1);
return res;
}
It needs no other information (it could do with a safety check on the size of key)
A quick guide to some of the options...
public class Foo {
public static void doo() {
}
private static void dont() {
}
public Foo() {
doo(); // this works
dont(); // this works
Foo.doo(); // this works
Foo.dont(); // this works
this.doo(); // this works but is silly - its just Foo.doo();
this.dont(); // this works but is silly - its just Foo.dont();
}
public static void main(String[] args) {
doo(); // this works
dont(); // this works
Foo.doo(); // this works
Foo.dont(); // this works
Foo foo = new Foo();
foo.doo(); // this works but is silly - its just Foo.doo();
}
}
public class Another {
public static void main(String[] args) {
Foo.doo(); // this works
Foo.dont(); // this DOESN'T work. dont is private
doo(); // this DOESN'T work. where is doo()? I cant find it?
}
}
Okay so I did search this question and a decent amount of results showed up. All of them seemed to have pretty different scenarios though and the solutions were different for each one so I'm a bit confused.
Basically, I have a Driver class that runs my program and contains the main method. I have a second class that has a few methods for editing a party (like party of characters in a game). What I wanted to do was this (part of main method)
System.out.println("Are you <ready> for your next battle? Or do you want to <edit> your party?");
Scanner readyScanner = new Scanner(System.in);
String readyString = readyScanner.next();
while(!readyString.equals("ready") && !readyString.equals("edit")) {
System.out.println("Error: Please input <ready> if you are ready for your next battle, or <edit> to change your party.");
readyScanner = new Scanner(System.in);
readyString = readyScanner.next();
}
if(readyString.equals("edit")) {
displayEditParty(playerParty, tempEnemy);
}
A lot of this is just some background code, the problem lies with
displayEditParty(playerParty, tempEnemy);
I get the error
Driver.java:283: cannot find symbol
symbol : method
displayEditParty(java.util.ArrayList<Character>,java.util.ArrayList<Character>)
location: class Driver
displayEditParty(playerParty, tempEnemy);
So, how could I call this method from another class in my main? In my code I use methods from other classes a few times, I'm a bit confused as to this one doesn't work.
You should make displayEditParty function public static and then you can use it in other class by className.displayEditParty(?,?);
Methods of class can be accessible by that class's object only. Check below code:
class A{
void methodA(){
//Some logic
}
public static void methodB(){
//Some logic
}
}
public static void main(String args[]){
A obj = new A();
obj.methodA(); // You can use methodA using Object only.
A.methodB(); // Whereas static method can be accessed by object as well as
obj.methodB(); // class name.
}
If your method is a static, you can call ClassName.methodName(arguments);
If your driver class not a static one you should create an instant of that class and call your method.
ClassName className=new ClassName();
className.displayEditParty(playerParty, tempEnemy);
I dont see where your declaring the Driver class in your code.
Driver foo = new Driver();
foo.displayEditParty(playerParty, tempEnemy);
I am new to Java and trying to do a simple program to help me further understand object-orientated programming.
I decided to do a phone program. However on line 5 of the following program where I'm trying to create an instance of a phone class I am getting the following error:
"No enclosing instance of type OOPTutorial is accessible. Must qualify the allocation with an enclosing instance of type OOPTutorial (e.g. x.new A() where x is an instance of OOPTutorial)."
Here is the program:
public class OOPTutorial {
public static void main (String[] args){
phone myMobile = new phone(); // <-- here's the error
myMobile.powerOn();
myMobile.inputNumber(353851234);
myMobile.dial();
}
public class phone{
boolean poweredOn = false;
int currentDialingNumber;
void powerOn(){
poweredOn = true;
System.out.println("Hello");
}
void powerOff(){
poweredOn = false;
System.out.println("Goodbye");
}
void inputNumber(int num){
currentDialingNumber = num;
}
void dial(){
System.out.print("Dialing: " + currentDialingNumber);
}
}
}
This may not make sense to you if you're new to Java, but a instantiating a non-static inner class (phone) requires an instance of the enclosing class (OOPTutorial).
In plain English, this roughly means that you either
Can only do new phone() inside a OOPTutorial-method that is not marked as static, or
you need to make phone a top level class (i.e. move it outside the scope of OOPTutorial), or
you need to make the inner class phone as static (by putting static in front of the class declaration)