Accessing method from different class - java

I'm trying to call a class's void from a different class. The objects work fine, but for some reason its not completing the action.
I'm making a black jack game, and I need some button to appear when the user enters a correct bet. Here is what I have:
public static void showButtons(Boolean x) { // to show or hide the buttons
if(x) {
hitButton.setVisible(true);
standButton.setVisible(true);
separator.setVisible(true);
}
else {
hitButton.setVisible(false);
standButton.setVisible(false);
separator.setVisible(false);
}
}
Once the bet is verified as an integer, it passes through this:
private void bdButtonActionPerformed(java.awt.event.ActionEvent evt) { //bdButton is the bet button
...
if(validBet(s)) {
bet = Integer.parseInt(s); // parses input string into an int
System.out.println("bet accepted"); // debug to know if it works this far
NewRound nr = new NewRound();
System.out.println("created object");
nr.newHand(bet);
//showButtons(true); // this works, it changes the buttons, but only from here
}
else {
...
}
}
Here is the newHand method:
public static void newHand(int bet) {
System.out.println("In newHand"); // debug
BlackJack b = new BlackJack();
b.showButtons(true);
System.out.println("passed showButtons"); // the code gets to here, but buttons are still not visible
}

The method is declared static, so assuming it is a class called TestClass, the way you would call the method looks like this:
TestClass.newHand(int bet);
If you want to be able to just call
newHand(int bet);
in your current class, you would need to use static import, like this:
import static your.package.TestClass.newHand;
But I would much prefer having it the first way.

Your newHand method is static, so it should be called with the class name.

Related

Using methods across all activities in android

I know there are already some questions on global methods and variables in android but I'm running into problems with static methods probably due to my less experience with objectoriented programming. So here is what I want to have:
I am writing an app which counts points which the user can earn for certain things he does. Because of that I want to call the method addPoints from different activities and services. This method should also set the points textview in the main activity and some other things.
I realized it by adding a static variable
static int sPoints;
in the MainActivity, that I use as a "global" variable in each activity.
However, with the addPoints method I have some problems. If I use a non-static method, I have to create an instance of MainActivity in the other activities, which is not very nice and changing the values of that instance does not have an effect on the actual MainActivity.
If I use a static function it works fine as long as I don't want to use non-static methods like in this example:
public static void addPoints(Context context, int points){
int levelBefore, levelAfter;
levelBefore = getLevelFromPoints(sPoints);
sPoints = sPoints + points;
levelAfter = getLevelFromPoints(sPoints);
if(levelBefore!=levelAfter){
String rank = getRankFromLevel(levelAfter);
levelTextView.setText("Lvl. " + String.valueOf(levelAfter));
Toast.makeText(context, "Congrats! You reached the next level!", Toast.LENGTH_LONG).show();
}
}
Here I can't easily use levelTextView.setText and I run into this problem in many other cases. Moreover, I've read that using static methods is not good, anyway.
So would the correct way be creating an instance of MainActivity each time and then call addPoints on it which has to return the new number of points? Or is there another way (I hope so, because both above ways seem to be not very satisfying).
a. Static methods can safely be used in case your work can not be accomplished by ShardPreferences and requires the use of same code at multiple classes like in your case.
b. First create an interface that will pass the updated rank to respective activities or classes
public interface ScoreUpdater {
void updateScore (String rank);
}
c. then implement it in all activities where required to use, MainActivity in this case
public class MainActivity extends AppCompatActivity implements ScoreUpdater{
//
//other methods and codes
//
#Override
public void updateScore(String rank) {
runOnUiThread(new Runnable() {
#Override
public void run() {
levelTextView.setText("Lvl. " + String.valueOf(levelAfter));
Toast.makeText(MainActivity.this.getApplicationContext(), "Congrats! You reached the next level!", Toast.LENGTH_LONG).show();
}
});
}
}
d. then implement your static methods. not sure where you have declared few variables. so my method below is on guess work.
public static void addPoints(Context context, int points){
//not sure where you are declaring sPoints
int levelBefore, levelAfter;
levelBefore = getLevelFromPoints(sPoints);
sPoints = sPoints + points;
levelAfter = getLevelFromPoints(sPoints);
if(levelBefore!=levelAfter){
String rank = getRankFromLevel(levelAfter);
if(context instanceof ScoreUpdater){
((ScoreUpdater)context).updateScore(rank);
}
}
}
private static int getLevelFromPoints(int points){
//your operations
return points;
}

Passing a method-reference to an objects constructor

I feel that I'm missing something when it comes to statically typed languages. When I pretty much only used perl way back, there were many ways I could tell an object which function to call.
Now that I'm in Java, I fail to see how I can do something similar in an easy fasion
I have a generic Button class. This is subclassed by all of the actual buttons that will be used: Each with a different method to call when clicked.
Is there really no way of passing a reference to a method to call when clicked, so that I can use one class for all of the buttons?
At present, I create buttons like this:
// Specifically using the subclass that sets "firemode" to "close"
FiremodeClose fc = new FiremodeClose(Settings.ui_panel_start, Settings.ui_panel_row_firemode, game);
painter.addSelectionButton(fc);
clickTracker.addSelectionButton(fc);
This ofcourse couses a myriad of subclasses, each one differing only in placement, label/graphics, and method call. It makes more sense to do something similar to this:
// Generic button, the method that sets "firemode" is somehow passed as arguement to the contsructor.
Button fc = new Button(&referenceToFunctionToCallWhenClicked, otherArguementsEtc);
painter.addSelectionButton(fc);
clickTracker.addSelectionButton(fc);
Like I said, I feel I must be missing something, because it makes sense that there should be a way of achieving this, thus letting me getting away with just one Button class without any subclasses.
If that's what interfaces are for, then I must've been using them for something else than their intended purpose. I'd love to see an answer involving some code examples for this.
Have your Buttons implement the observer pattern, just like Swing does. Then you can even just use Swing's ActionListener interface, or even Runnable is not a bad choice, or e.g. roll your own:
// Your interface.
public interface MyButtonListener {
public void buttonClicked ();
}
// Somewhere else:
Button fc = ...;
fc.addButtonListener(new MyButtonListener () {
#Override public void buttonClicked () {
// do stuff here
}
});
// And in your Button have it simply iterate through all of its registered
// MyButtonListeners and call their buttonClicked() methods.
There are myriads of other ways to implement this. For example, you could even do something like:
public interface ThingThatCaresAboutButtons {
public void buttonClicked (Button button);
}
Then have your higher level UI logic be something like:
public class MyUI implements ThingThatCaresAboutButtons {
#Override public void buttonClicked (Button button) {
if (button == theOneButton) {
// do whatever
} else if (button == theOtherButton) {
// do whatever
}
}
}
And when creating buttons:
theOneButton = new Button(theUI, ...);
theOtherButton = new Button(theUI, ...);
Or have them maintain a list instead of a single object passed in the constructor. Or whatever.
Endless ways to skin this cat but hopefully you get some inspiration here. Check out how Swing works.
You could for instance use Runnable:
class MyButton {
private final Runnable action;
public MyButton(Runnable action) {
this.action = action;
}
...
}
And then call action.run() when the button is clicked.
Then when creating a button, you can pass a reference to a method, as long as it has the void return type, and takes no arguments.
Button fc = new Button(EnclosingClass::methodToCall, otherArguementsEtc);
Other interfaces can be used for different method signatures.
In Java 8 you can use both method references and lambdas:
class Button {
Button(Runnable function) {
}
}
Button b1 = new Button(() -> System.out.println("works!"));
Button b2 = new Button(System::gc);
You can do similar thing in Java <8, but it's more verbose with anonymous classes:
Button b3 = new Button(new Runnable() {
#Override
public void run() {
System.out.println("works!");
}
});

How to find out whether Method has called for given instance. Like "Object obj" check whether obj called "equals" method or not

I want to find out whether method for some object is being called for that instance or not.
Is it possible in java ?
Like ...
class Button {
public void focus(){}
public void setName(){}
}
class MyTest {
public static void main(String[] args){
Button button = new Button();
button.focus();
// I want to find out on button instance whether focus() or setName() is called or not.
whetherMethodCalled(button);
// OR
whetherMethodCalled(button, 'focus');
whetherMethodCalled(button, 'setName');
}
}
EDIT : Forgot to add Button class is third party class which I cannot modify... Also I want to check in my code whether method has called for given object instance or not on basis of that I have to write some code.
In order to reduce extra work, perhaps profiling your application with JConsole or another tool is good enough to show if certain methods have run. Another option is using a code coverage tool like EMMA which detects dead code. There is a list of open-source profilers for Java at http://java-source.net/open-source/profilers and EMMA is at http://emma.sourceforge.net/.
With some extra work AspectJ could be use to intercept method calls without changing existing code. For example, the following would intercept calls to Button.focus()
#Aspect
public class InterceptButtonMethods {
#Before("execution(* Button.focus())")
public void beforeInvoke() {
System.out.println("Button.focus invoked");
incrementFocusCount();
}
}
If more extra work is ok, there is a way to wrap all calls to the Button's focus() and setName() methods so that they update separate counters in addition to their normal functions. This can be done by extending Button in YourButton class which is identical to Button except for a couple of int counters with getters, setters and increment methods; and countingFocus() and countingSetName() methods which update their counters and call focus() and setName() respectively, such as in outline:
Class YourButton extends Button {
int focusCount;
int setNameCount
int getFocusCount() {return this.focusCount;}
void setFocusCount(int counter) {this.focusCount = counter} // optional to reset counter
void incrementFocusCount() {this.focusCount = getFocusCount() + 1;)
...
void countingFocus() {
incrementFocusCount();
focus()
}
...
}
If it is required in many places and involves complex things, I recommend to use Mockito to test your code. Using that you can verify if the method was invoked (also how many times if invoked)
You can mock the button and verify in your MyTest how many times the method must be called. Using Mockito you can mock and stub your methods(Stubbing voids requires different approach from when(Object) because the compiler does not like void methods inside brackets) and then verify it using verify statement.
verify(mockButton, times(1)).focus();
verify(mockButton, times(1)).setName();
You can write a wrapper class over the 3rd party Button class through which all calls to Button class will be made.
This wrapper class can keep track of whether each method has been called or not
class ButtonCaller {
private Button button = null;
private boolean focusCalled;
private boolean setNameCalled;
public ButtonCaller() {
button = new Button();
focusCalled = false;
setNameCalled = false;
}
public void focus() {
button.focus();
focusCalled = true;
}
public void setName() {
button.setName();
setNameCalled = true;
}
public void whetherMethodCalled(ButtonMethod method) {
switch (method) {
case FOCUS:
return focusCalled;
case SET_NAME:
return setNameCalled;
}
throw new RuntimeException("Unknown ButtonMethod !!!");
}
public static Enum ButtonMethod {
FOCUS,
SET_NAME;
}
}

How to call an Object's Method from another class without creating a sub-class and/or inheriting class?

I've been learning basic code at a very beginner level. Now I'm finally starting to dabble in actually writing simple programs, and got really stuck.
I'm writing a simple a program that consists of two classes; People,
MainPage.
Once the program runs, the method openApp() is called in main method from (MainPage Class).
public static void main(String[] args) {
openApp();
}
Next, when the openApp() is called, the user has three menus to choose to go to that are selected by entering the corresponding number
i.e. 1 = Newsfeed, 2 = Profile or 3 = Friends.
public class MainPage {
public static void openApp() {
System.out.println("Welcome to App!");
System.out.println();
System.out.println("To Select Option for:");
System.out.println("Newsfeed : 1");
System.out.println("Profile : 2");
System.out.println("Friends : 3");
System.out.println("Enter corresponding number: ");
int optionSelected = input.nextInt();
switch (optionSelected) {
case 1: System.out.println("NewsFeed");
break;
case 2: System.out.println("Profile");
break;
case 3: System.out.println("Friends");
break;
if (optionSelected == 3) {
people.friend();// Is it possible to write: friend() from "People" Class without extending to People Class
}
}
}
If User selects "friends" then the program calls a method from
People Class called friend(People name) in MainPage class that prints out people object's friends.
My Attempt:
if (optionSelected == 3) {
people.friend();
}
The Error I get:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
people cannot be resolved
Problem is I don't want to extend People Class in MainPage and inherit all it's methods, yet I still want to call an Object method from People Class to print people object's friends.
Note: just in case anyone would want to look at the friend(People people) method that is located in the People class:
public void friend(People people) {
System.out.println(people.friend);
Excellent question format.
You can declare an Object of type People, and use that.
Example
public class MainPage
{
People people = new People();
// .. Some code.
if(optionSelected == 3) {
people.friend();
}
}
Explanation
Your friend method is an instance method. This means that in order to access it, you need to have an instance of the object created. This is done with the new keyword. Secondly, unless People is some form of utility class, then your friend method should probably read more like:
public void friend()
{
System.out.println(this.friend);
}
And for the sake of good code design, remember that your MainPage class is outputting to the user, so you should return the value rather than print it. Secondly, you should conform to good naming standards, and in Java we use the get prefix when getting a class member.
public void getFriend()
{
return this.friend;
}
and in the MainPage class, you should print this.
if(optionSelected == 3)
{
System.out.println(people.getFriend());
}

Method Generator in java

I am using Kmax to create a DAQ software. The philosophy of the GUI and the code is that every object on the GUI(radio buttons, check boxes, progress bars etc) has to have the same name with the relevant method. For instance an object named BUTTON is linked with the method public void BUTTON(KmaxWidget widget){code}.
My code is
import kmax.ext.*;
public class Runtime implements KmaxRuntime {
KmaxToolsheet tlsh; // Store a reference to the toolsheet environment
KmaxHist hist1D;
KmaxWidget checkBoxWidget;
public void init(KmaxToolsheet toolsheet) {
tlsh = toolsheet; // Save this reference for use in the toolsheet
hist1D = tlsh.getKmaxHist("HIST1D");
checkBoxWidget = tlsh.getKmaxWidget("CHECK_BOX_CALIB_METH");
tlsh.getKmaxWidget("CHECK_BOX_CALIB_METH").setProperty("VALUE", "1");
}
public static boolean stringToBool(String s) {
if (s.equals("1"))
return true;
if (s.equals("0"))
return false;
return true;
}
public void CalibInit(KmaxWidget widget, KmaxHist histo){
histo.setUseXAxisCalibration(stringToBool(widget.getProperty("VALUE")));
histo.update();
}
public void chooseCalib(){
checkBoxWidget = tlsh.getKmaxWidget("CHECK_BOX_CALIB_METH");
checkCalib(checkBoxWidget,hist1D);
}
public void GO(KmaxToolsheet toolsheet){}
public void SRQ(KmaxDevice device) {}
public void HALT(KmaxToolsheet toolsheet) {}
} // End of the Runtime object
In the above code I have the check box CHECK_BOX_CALIB_METH. The problem arises when someone wants to create many objects;one has to create many methods. In the above code you can see what I am trying to do. I want to create a "main" method that will do every function that is needed and then another method will apply those functions to each object.
This code compiles without any errors, but the check box isn't working. So I was thinking if there is a way around this. For instance a method that will include "submethods" that will do the job! Or perhaps a method that will construct methods in a for loop for each radio button, check box, progress bar etc. Something like
for(int i=0; i<number_of_buttons ; i++){public void BUTTON_i(){code}}
The above code may look ridiculous but I don't know what else to think and I really want to avoid having one method for each button.
Is something like that possible or is there another way around this?
EDIT
For instance I have 6 methods that do exactly the same;they just have different names.
public void SET_CALIB_1(KmaxWidget widget) {
double C0 = (getValueFrom("Ch2_1")*getValueFrom("En1_1")-getValueFrom("Ch1_1")*getValueFrom("En2_1"))/(getValueFrom("Ch2_1")-getValueFrom("Ch1_1"));
double C1 = (getValueFrom("En2_1")-getValueFrom("En1_1"))/(getValueFrom("Ch2_1")-getValueFrom("Ch1_1"));
double C2 = 0;
double[] coef = {C0, C1, C2};
hist1.setXCalibration(coef);
hist1.setUseXAxisCalibration(true);
hist1.update();
} // SET_CALIB_1
Is there a way to have a generator method to generate methods like the above?
what are the design goals for this software?
reflection may be a much better way to get access to the members; and/or put all the components into an array for access.
I find that I tend to over-engineer things a lot; since I enjoy building things; but then they get way too complicated and don't work.
so I advise to take a walk (or trudge through the snow) and think about it some more.

Categories