How do I call this parameter in another class? - java

I'm trying to call the static method getPod in the class DropPod from another class with DropPod.getPod() except I need a parameter for DropPod.getPod().
How do I change the getPod method so I can access it from the other class?
I know I could just make land() static, but I don't want to do that. I'd like to try to learn to do it this way.
public class DropPod {
protected static boolean opened;
int pos = Random.NormalIntRange(1777, 1794);
public static void getPod(DropPod drop)
{
drop.land();
}
public void land() {
Level.set(pos, Terrain.DROPPOD_CLOSED);
Game.updateMap(pos);
opened = false;
Dungeon.observe();
}
}

Option 1: You can create a new instance of DropPod in your other class. With this instance, you can just call Object.getPod().
Option 2: You already mentioned this, but you could make land a static method as well and DropPod.getPod() should work.

Static methods of a class cannot reference non-static methods of its objects.
If you only want 1 instance of DropPod, you can add it as a property of it's own class. Something like a Singleton Pattern.

Add a non-static overload for getPod() with no parameters, that just calls land().
Maybe remove the static version completely. Hard to see why this method exists at all actually, or why it is called getPod() when it doesn't return anything. I would remove it and just call land() directly.
Also hard to see why you want to call a method that calls land() when you don't have anything to land. You need to rethink all this.

Related

Why am I being forced to change methods and varibles to static when calling them from my main method? [duplicate]

This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
Cannot make a static reference to the non-static method
(8 answers)
Closed 5 years ago.
For some reason when I'm trying to call methods using a main method or try changing variables declared outside the main method I get forced into having to change everything to static. This is fine in places but when it comes to needing to change values later in the code for example using a Scanner for input the main method just takes it to a whole new level trying to make me change the Scanner library etc.
This example shows what happens if I try calling a method.
This example shows what happens when I try alter the value of a variable declared outside my main method.
I have never faced an issue like this before when writing java code I've tried recreating the classes/ project files etc but nothing works. I've tried looking everywhere for a solution but I can't seem to find one probably due to the fact that I don't know what to search for. I've probably made myself look like a right idiot with my title haha! Any suggestions people?? Thanks in advance!
Maisy
It can be a bit confusing to get out of "static land" once you are in your main() method. One easy way is to have another object contain your "real" (non-static) top level code and then your main method creates that object and starts it off.
public static void main() {
MyEngine engine = new MyEngine();
// core logic inside of start()
engine.start();
}
I hope that this was clear enough for you. Good luck Maisy!
When calling methods form a main you have to instantiate the class they are in, unless it's a static function
this is because that a class is a sort of template and there is nothing saved about it before it get instantiated
public class TestClass{
public static void main(String[] args){
TestClass testClass = new TestClass();
testClass.method();
}
public method method(){}
}
in the example above i instantiated a TestClass and then called on the testClass instance
there is some functions and variables on classes you might want static, because a static on a class is shared between ALL instances, and can be called on the class, say you want to know how many instances were created then something like this can be done.
public class TestClass{
public static void main(String[] args){
TestClass testClass = new TestClass();
testClass.method();
System.out.print(TestClass.instances +""); // note that i call on
//the class and not on an instance for this static variable, and that the + ""
//is to cast the int to a string
}
public static int instances = 0; // static shared variable
public TestClass(){instances++;} // constructor
public method method(){}
}
You need to do some Object Oriented Programming tutorial and to learn some basic.
As answer for your problem to call without using static you have to create an instance of the main Class
let suppose the following class Foo
public class Foo{
private int myVarInteger;
public int getMyVarInteger(){ return this.myVarInteger;}
public void setMyVarInteger(int value){this.myVarInteger = value;}
public static void main(String[] args){
Foo myClassInstanceObject = new Foo();
// now we can access the methods
myClassInstanceObject.setMyVarInteger(5);
System.out.println("value ="+myClassInstance.getMyVarInteger());
}
}

accesing private static method from another

I have main class with a private static method. I want to access this method from another java class. I tried some ways,however they didnt work. How can I access the method?
below main class like this;
public class RandomGenerate {
public static void main(String[] args) throws Exception {
System.out.print.ln("main method");
}
private static synchronized void createRandom(PersonObj person, int number, List s) {
System.out.println("deneme");
}
}
And I want to call createRandom from another java class like this;
public class Deneme {
RandomGenerate rg = new RandomGenerate();
RandomGenerate.createRandom(person, number, sList);
}
Then, netbeans shows method has private access.
You shouldn't access a private function/variable from outside of that class. If you need to access a private variable of a class, you can create an accompanying getter for that variable, and call the getter function on the class.
For functions, if the class you are trying to access the function from is in the same package, or is a subclass as the class with the function, change private to protected. protected allows members in the same package, or subclasses, to access the item, but nothing outside of the package.
A good read on visibility in Java is: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
That shows a table:
Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
Primarily
If you need to use it outside the class, make it public (or protected if you need it only in subclasses, or the default [no keyword at all] if you need it just in the package). If you need to use it outside the class and it's private and you can't make it not private, that's a design problem you should fix.
But...
...you can work around it using reflection (tutorial, docs), which allows you to get the method and call it even though it's private. Once you have the Method object, you have to call setAccessible to true before you call it.
But again, that's a workaround. Use the correct access modifier.
private methods are not accessible from another class by definition. If you need to call it you can create another public method that internally calls the private one or change the access modifier to public/protected/default.Example:
private static String secretMethod() { return "secret"; }
public static String knownMethod() { return secretMethod(); }
You will want to choose the proper access modifier for the method, the options are: public, protected, default (which is indicated by not providing a modifier), and private.
A good explanation is here: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
As mentioned in the comments, you can use public to open it up, but if you don't want such a wide access, you could start with default (which allows you to access the method if you're in the same package), or protected (which is the same as default, but also allows child classes to access the method, if you wanted to extend the class).
As a general rule, stick with the most restrictive permission. It's easier to open up permissions later, but very hard to remove them.
You can not access Private methods outside the class which defines this method. You should make it Public to give full access to any classes or protected to give access to all the classes in the same package.
Click [here] http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html For more reference.
If you really wish to access private method, you will have to use Java Reflection. See this sample code.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Workspace {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
ClassWithPrivateMethod cwpm = new ClassWithPrivateMethod();
Method m = cwpm.getClass().getDeclaredMethod("privateMethod", String.class);
m.setAccessible(true); //This is a key statement for accessing private methods
m.invoke(cwpm, "test");
}
}
class ClassWithPrivateMethod {
private void privateMethod(String someParam){
System.out.println("I am private!!!");
System.out.println("Parameter: " + someParam);
}
}
This code will print following output:
I am private!!!
Parameter: test
Just change the visibility from private to public so other Instances can access them. Private means it is only for the own class available.

What is the most conventional way to change my variable value in Java?

In a class I have something along the lines of the following:
public class MyClass {
private static boolean running;
public static void main(String[] args) {
//setRunning(false);
//running = false;
}
public static void setRunning(boolean running) {
MyClass.running = running;
}
}
I was wondering what the most conventional way of changing the value of 'running' is, seen as I have access to using the setter method that I use in other classes, as well (somewhat)direct access to changing the variable value without calling a method.
I understand that simply doing running = false; may be more efficient (correct me if I'm wrong) but I am unsure on what the convention is for a class to change its own local variable where others would use its setter method.
I don't exactly understand what you're question is. I think you're asking how classes should alter their own variables.
If that is the case, classes should not invoke their own Getter or Setter methods for local variables, just accessing the variable directly should suffice.
Edit: this may be a stylistic thing, but I suggest using the "this" keyword in your Setter instead of "MyClass"
So instead of MyClass.runner = runner, use this.runner = runner;
If running is used outside of the class, then it has to be public static boolean running;
Inside of the class, saying running = false would do just fine.

Java/Android: Method with Full Project Scope

I have a method that I've created that I would like to be able to use anywhere, but I don't know what the best practice is for giving access to that method throughout the project. Do I just create a .java file with a public method and that will give access throughout? Will I need to declare it anywhere (somewhere in the manifest?)?
I'm sure this has been asked, but I am not returning anything useful on my google searches. I am not good enough at googling for Android, yet! Sorry for adding to the duplicates, if I am.
You have a few options. The simplest is a public static method.
public class MyClass {
public static MyReturnType myMethod(MyArgumentType input) {
// my code here
}
}
You will now be able to call this like:
MyClass.myMethod(arg);
Use static methods. As for me, if I want to store just methods in the same place I create a new class and all of the methods are static. For example.
public static int parseInt(String str)
{
try
{
return Integer.parseInt(str);
}
catch (NumberFormatException e)
{
return -1;
}
}
If it's just do anything and doesn't require to save state in the class, this is the best solution.
Here's a sample of a static method.
public class Messages {
public static String mySpecialFinalMessage(){
return "Hello Stackoverflow";
}
}
You no longer need to create an Instance of Messages to call mySpecialFinalMessage() because it is a static. The best practice to call a static method is in this format CLASSNAME.STATICMETHODNAME();
So in our example,
Messages.mySpecialFinalMessage()
Please Note that you calling static methods inside non-static method is legal however, calling non-static methods inside static methods will give you a compile time error.
this is legal
public class MyMessage {
public String getMessage(){
return Messages.mySpecialFinalMessage();
}
}
Take note taht Messages.mySpecialFinalMessage() is that static method. Also, Notice that we did not create an instance of Messages to call mySpecialFinalMessage(), rather we've just called it directly by CLASSNAME.STATICMETHODNAME

How to use this keyword in a static method in java?

Is there any way to use this keyword inside a static method in Java? I want to display a Toast message inside a static method in my activity class. How do I do that? Thanks.
Now what?
static void thisInStatic(){
new Object(){
Object instance = this;
};
}
You can create a static method with one input parameter that is the Class you need to use.
For example:
public static void showMyTouch(MyActivity act, String message){
Toast.makeText(act, message, Toast.LENGTH_LONG).show();
}
No. There is nothing for it to refer to.
I believe that "this" represents the object that invokes the method. Static methods are not specifically bound to any particular object. Rather, they are class level methods. That is why "this" cannot be used in static methods.
this refers to instance members and static method will only access static variable
This refers to the object that will be created. You can't access such object from staitc method. Put you attention on it. Here some useful link to you http://mindview.net/Books/TIJ4

Categories

Resources