Java/Android: Method with Full Project Scope - java

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

Related

How to handle static in java

I got into programming a bit obliquely with Bukkit and thus didn't learn some things properly. But since I've been doing real stuff for a while now I wanted to ask how to deal with static.
I know that you should avoid static as most as possible.
Should you then call external functions like this?
//Another Class
public void exampleMethodInAnotherClass() {
system.out.prinln("Hi :D");
}
//Main
public static void main(String[] args) {
new AnotherClass().exampleMethodInAnotherClass();
}
//OR
public static void exampleMethodInAnotherClass() {
system.out.println("Hi :D");
}
public static void main(String[] args) {
AnotherClass.exampleMethodInAnotherClass();
}
Now it's about the type of function that you use if the function is too much used in your code like System.out.println then make it static *(static function are mostly common in maths and helper classes).
OH the static keyword , My most hero in the programming!
I know that you should avoid static as most as possible.
no that's not true in the most cases the programmer that are student or new in the programming think it's best Idea that we have use static key but it's important to know the why we use static.
after you use static key the variable imidediately going to memory and you can accsess it directly by calling the refrence! and it's the package and class with the variable name but the static method is in the memory and if you change it from some where in your code the data change , see some example :
public class Test {
static String MESSAGE= "";
public static setMessage(String message){
MESSAGE = message;
}
public static void showMessage(){
System.out.println(MESSAGE);
}
}
----------------
Calling from another class
public static void showMessage(){
System.out.println(Test.MESSAGE);
}
if you run the program and change the message with the showMessage method you can get the message and if you need you can call the MESSAGE by reference Like ClassName.MESSAGE or create object from your class with new Keyword but your MESSAGE variable is static and in your memory after running your code so the use new keyword to call it not nesssasery and you can call it directly ! remember using the static variable in mini or script cases or test is good idea but if you create Enterprise project using static method or variable without knowledge about it it's bad idea! because , I most use static keyword for method or variable I need always return same result or work straight work I need! like show the time , convert date or etc... but don't use for changing the data The example I share it's good ref for know the problem.
Good ref for know the static internal work it's here

How do I call this parameter in another class?

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.

Java Getting String from another class returning null

I currently have two constructors in one of my classes, one going to my main class, and the other to another class that has most of the methods that I use. The reason I don't use static methods for my second class that I have a constructor, is that I don't want the code to be used by any other source, just mine. Here are the two constructors:
PrisonProfessionalMain plugin;
public PPCommandAdminMenu(PrisonProfessionalMain instance)
{
plugin = instance;
}
QuickMethods qm;
public PPCommandAdminMenu(QuickMethods instance)
{
qm = instance;
}
Then I am calling a method from the QuickMethods class here:
qm.getConfigString(plugin, "prefix")
Apparently, whatever method I call from this class it returns null. I do not think it is what I put inside of the method, but here is the method from the other class:
public String getConfigString(PrisonProfessionalMain instance, String configvar)
{
return colorize(instance.getConfig().getString(configvar));
}
I don't see a problem here, but I am wondering if I should use a static way instead. I want to try and stay away from static methods for the reason I stated above.
REMEMBER: Calling any other method from this class results in it returning null. I know this because in console it has a stack trace that reads it null. It says this on the line that is calling any method from this class.
I tried removing the Strings and instances from inside the method:
public String getConfigString()
{
return System.out.println("test");
}
This still however, resulted in another null pointer, pointing at the line that I called the method on.
My question is: How would I have the QuickMethods class stop returning null upon calling methods/strings from it.
Only one constructor can be called at a time, given your code it appears you need to combine your constructors like,
QuickMethods qm;
PrisonProfessionalMain plugin;
public PPCommandAdminMenu(PrisonProfessionalMain plugin, QuickMethods qm)
{
this.plugin = plugin;
this.qm = qm;
}
Otherwise (by definition) one will be null.
Also,
public String getConfigString()
{
return System.out.println("test");
}
isn't legal code because PrintStream.println() is void (and System.out is a PrintStream). You can use something like
String str = "test";
System.out.println(str);
return str;

Accessing public methods of a Private Inner Class, from outside the Enclosing class

I have the following code class Agent.java :
public class Agent {
Helper helper ;
private class SpecificBehaviour extends Behaviour{
private Apple a;
public SpecificBehaviour(Apple a){
setApple(a);
}
public void setApple(Apple a){
this.a=a;
}
public Apple getApple(){
return a;
}
}
public void someMethod(){
helper = new Helper(this);
}
}
In the Helper.java ( another class within the same package) I would like to access the getApple() method. did some search and found this link
I am wondering if there is a better/ easier way of doing this ?
There are at least two issues here:
Helper doesn't know of the existence of SpecificBehaviour, because it's a private class. It could potentially know about the Behaviour class, which you haven't given any details of. If getApple() is declared in Behaviour, and if Behaviour is visible to Helper, then the visibility part needn't be a problem.
Helper will need a reference to an instance of SpecificBehaviour, which means you'll need to instantiate SpecificBehaviour. For that, you'll also need an instance of Agent, because SpecificBehaviour is an inner class. It's not clear whether you have such an instance.
Basically I think the presence of a private inner class is adding confusion here. If you're reasonably new to Java, I'd strongly recommend sticking to top-level classes for the moment. They have a few subtleties around them, and it's best to try to learn one thing at a time.
If this doesn't help, please give more context - your question is quite vague at the moment. Where do you want to use getApple within Helper? Should part of the state of Helper be a reference to an instance of SpecificBehaviour, or should it be a method parameter? Have you created an instance of Agent? What does Behaviour look like? You may find that in the course of answering these questions one at a time, you're better able to figure out the problem for yourself.
- Use Composition principle to get the access to the getApple() method.
Eg:
public class Agent {
Apple a = new Apple(); // Agent class has a reference of type Apple.
.....
.....
}
- Second way would be to make the getApple() method static in Apple class, and then access it from Agent class using the Class name with . (dot) operator.
Eg:
public class Agent {
public void go(){
Apple.getApple();
}
.....
.....
}
You need to ask the Agent object you are passing to the Helper for the instance of the private class SpecificBehaviour. This is the way it works. Encapsulation remember.
Jon Skeet stated that and I completely agree on it:
Helper will need a reference to an instance of SpecificBehaviour,
which means you'll need to instantiate SpecificBehaviour. For that,
you'll also need an instance of Agent, because SpecificBehaviour is an
inner class. It's not clear whether you have such an instance.
Actually, you can understand how weird your try is by testing the sample code below:
Agent.java
public class Agent
{
private class SpecificBehaviour
{
public String toString()
{
return "specific behaviour";
}
}
public Class getInner()
{
return SpecificBehaviour.class;
}
}
Helper.java
public class Helper
{
public static void main(String[] args)
{
try
{
Agent agent = new Agent();
System.out.println(agent.getInner().newInstance().toString());
}
catch (InstantiationException e) { e.printStackTrace(); }
catch (IllegalAccessException e) { e.printStackTrace(); }
}
}
The code above just compiles fine. And let's see what the output is:
java.lang.InstantiationException: Agent$SpecificBehaviour
at java.lang.Class.newInstance0(Class.java:340)
at java.lang.Class.newInstance(Class.java:308)
at Helper.main(Helper.java:5)

Need help to get two classes to assist each other

i'm currently just fooling around with different classes to test how they work together, but im getting an error message in NetBeans that i cant solve. Here's my code:
class first_class.java
public class first_class {
private second_class state;
int test_tal=2;
public void test (int n) {
if (n>2) {
System.out.println("HELLO");
}
else {
System.out.println("GOODBYE");
}
}
public static void main(String[] args) {
state.john();
TestingFunStuff.test(2);
}
}
class second_class
public class second_class {
first_class state;
public int john () {
if (state.test_tal==2) {
return 4;
}
else {
return 5;
}
}
}
Apparently i can't run the method "john" in my main class, because "non static variable state cannot be referenced from a static context" and the method "test" because "non static method test(int) cannot be referenced from a static context".
What does this mean exactly?
Screenshot of the error shown in netbeans: http://imageshack.us/photo/my-images/26/funstufffirstclassnetbe.png/
It means state must be declared as a static member if you're going to use it from a static method, or you need an instance of first_class from which you can access a non-static member. In the latter case, you'll need to provide a getter method (or make it public, but ew).
Also, you don't instantiate an instance of second_class, so after it compiles, you'll get a NullPointerException: static or not, there needs to be an instance to access an instance method.
I might recommend following Java naming conventions, use camelCase instead of under_scores, and start class names with upper-case letters.
The trick here to get rid of the error message is to move the heavy work outside of main. Let's assume that both lines are part of a setup routine.
state.john();
TestingFunStuff.test(2);
We could create a function called setup which contains the two lines.
public void setup() {
state.john();
TestingFunStuff.test(2);
}
Now the main routine can call setup instead, and the error is gone.
public static void main(String[] args) {
setup();
}
However, the other members are correct in that your instantiation needs some cleanup as well. If you are new to objects and getting them to work together might I recommend the Head First Java book. Good first read (note first not reference) and not all that expensive.
Classes can have two types of members by initialization: static and dynamic (default). This controls the time the member is allocated.
Static is allocated at class declaration time, so is always available, cannot be inherited/overridden, etc. Dynamic is allocated at class instantiation time, so you have to new your class if you want to access such members...
It is like BSS vs heap (malloc'd) memory in C, if that helps..

Categories

Resources