How to Make Method Call Another One in Classes

Java how to call method in another class

You declare a Cypher type static variable c here. so you can't access the Cypher class method using c variable without object declaration. But you can call the c variable from any class because it's a static variable. But your Cypher class don't have any static Method so you can't call these methods without object initialization.
So you must declare a static method or need to create an object for the access method from Cypher class.

But if you declare Cypher type static variable with initialization. then you can call c from any class and also called Chyper class method using the c variable reference. like:

// Declare this on Runner class
public static Cypher c = new Cypher();

// And then call from any class like
Runner.c.yourMethod();

Happy Coding.

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
public static void Method2()
{
// code here
}
}

class Caller
{
public static void Main(string[] args)
{
AllMethods.Method2();
}
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
public void InstanceMethod()
{
// ...
}
}

public static void Main(string[] args)
{
var instance = new MyClass();
instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
public class AllMethods
{
public static void Method2()
{
// code here
}
}
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
class Caller
{
public static void Main(string[] args)
{
Method2(); // No need to mention AllMethods here
}
}
}

Further Reading

  • Static Classes and Static Class Members (C# Programming Guide)
  • Methods (C# Programming Guide)
  • using static directive (C# Reference)

Call Class Method From Another Class

update: Just saw the reference to call_user_func_array in your post. that's different. use getattr to get the function object and then call it with your arguments

class A(object):
def method1(self, a, b, c):
# foo

method = A.method1

method is now an actual function object. that you can call directly (functions are first class objects in python just like in PHP > 5.3) . But the considerations from below still apply. That is, the above example will blow up unless you decorate A.method1 with one of the two decorators discussed below, pass it an instance of A as the first argument or access the method on an instance of A.

a = A()
method = a.method1
method(1, 2)

You have three options for doing this

  1. Use an instance of A to call method1 (using two possible forms)
  2. apply the classmethod decorator to method1: you will no longer be able to reference self in method1 but you will get passed a cls instance in it's place which is A in this case.
  3. apply the staticmethod decorator to method1: you will no longer be able to reference self, or cls in staticmethod1 but you can hardcode references to A into it, though obviously, these references will be inherited by all subclasses of A unless they specifically override method1 and do not call super.

Some examples:

class Test1(object): # always inherit from object in 2.x. it's called new-style classes. look it up
def method1(self, a, b):
return a + b

@staticmethod
def method2(a, b):
return a + b

@classmethod
def method3(cls, a, b):
return cls.method2(a, b)

t = Test1() # same as doing it in another class

Test1.method1(t, 1, 2) #form one of calling a method on an instance
t.method1(1, 2) # form two (the common one) essentially reduces to form one

Test1.method2(1, 2) #the static method can be called with just arguments
t.method2(1, 2) # on an instance or the class

Test1.method3(1, 2) # ditto for the class method. It will have access to the class
t.method3(1, 2) # that it's called on (the subclass if called on a subclass)
# but will not have access to the instance it's called on
# (if it is called on an instance)

Note that in the same way that the name of the self variable is entirely up to you, so is the name of the cls variable but those are the customary values.

Now that you know how to do it, I would seriously think about if you want to do it. Often times, methods that are meant to be called unbound (without an instance) are better left as module level functions in python.

Calling method in another class

You are misusing inheritance, and this fundamental issue is causing your code not to work. In your class above you have

calculation extends tripCostCalculatorUI

you have the calculating class extend the GUI, with hopes that the GUI fields can then be used in your calculation, but this is not what inheritance is for -- it's not present to allow you to connect data, but rather to extend behavior. Yes, your current inheritance set up will allow you to access JTextFields, but (and this is key), these JTextFields are not the same as the ones displayed in the GUI, since they're part of a completely different instance. Your calculation class does not satisfy the "is-a" relationship with the GUI class, and so should not extend it.

Rather, instead you should give the calculation class (which should be renamed Calculation, as all class names should begin with an upper-case letter) methods that take numeric parameters that allow other classes that use this class, including the Gui class, the ability to pass data into the calculation methods, and then get the results that they return.

And so Calculation should use no JTextField variables and instead use the values passed into its calculation method parameters.

So within the GUI's ActionListener, the GUI itself will extract data from its components, convert anything that needs conversion to numeric values, call the appropriate method from the Calculation class to allow a calculation, and then display the result that is returned (after converting the result to text).

Here's a simple example of just what I mean where the GUI and the calculation classes are separate, where you use method parameters:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class SimpleCalcGui extends JPanel {
private static final long serialVersionUID = 1L;
private JTextField field1 = new JTextField(5);
private JTextField field2 = new JTextField(5);
private JTextField resultField = new JTextField(5);
private JButton calcButton = new JButton("Calculate");

public SimpleCalcGui() {
resultField.setFocusable(false);
calcButton.addActionListener(new CalcListener());

add(field1);
add(new JLabel("+"));
add(field2);
add(new JLabel("="));
add(resultField);
add(calcButton);
}

private class CalcListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
try {
// extract the values and convert to numbers
int value1 = Integer.parseInt(field1.getText());
int value2 = Integer.parseInt(field2.getText());

// call MyCalc's method passing in the values
int result = MyCalc.addition(value1, value2);

// display the result
resultField.setText("" + result);

} catch (NumberFormatException e1) {
JOptionPane.showMessageDialog(calcButton, "Both text fields must have valid numbers",
"Numeric Entry Error", JOptionPane.ERROR_MESSAGE);
field1.setText("");
field2.setText("");
}
}
}

public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}

private static void createAndShowGui() {
SimpleCalcGui mainPanel = new SimpleCalcGui();
JFrame frame = new JFrame("SimpleCalcGui");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}

public class MyCalc {
// overly simple but just to show what I mean
public static int addition(int value1, int value2) {
return value1 + value2;
}
}

Calling method of Another class from run() method

A common problem with ScheduledExecutorService is that if the scheduled command throws an exception, the exception is silently swallowed. The code in the question does not seem to throw exceptions, but in more complex code it is difficult to avoid (for example unexpected NullPointerExceptions)

A quick fix is to put all of the Runnable.run method in a try-catch block:

public class SomeMinuteJob implements Runnable {
@Override
public void run() {
try {
System.out.print("Inside run method");
ReadData obj = new ReadData();
obj.readData();
System.out.println("After reading data");
} catch (Exception e) {
// Log exception
e.printStackTrace();
}
}
}

How do you call a method in one class, from another class?

I'm assuming that you've got a WinForms app and Form1 is the default form class created in your project.

In this case what's likely going on is your application Main method is creating an instance of Form1 and displaying it. However, your Enemy class is creating its own instance of the Form1 class:

Form1 form1 = new Form1();

That's a completely different instance from the one that's being displayed. You need to give your Enemy the instance that's being displayed. Perhaps the easiest way to do that is by having Form1 create an instance of Enemy and pass this to it. For example:

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

_enemy = new Enemy( this );
}

private Enemy _enemy;
}

And then your Enemy class would look something like this:

public class Enemy
{
public Enemy( Form1 form )
{
_form1 = form;
}

// DON'T initialize this with new Form1();
private Form1 _form1;
}

Now when your Form1 gets created, it will create an instance of Enemy which will then get a reference to the form.

Calling method from another class - Winforms C#

If you just want put some code in a function, you should declare the function like

public static class MyClass{
public static void MyMethod(){...}
}

If you only need the method from within the same project you can replace public with internal.

A static method is appropriate if the method only depends on the given parameters, if it needs to maintain a state you need to remove the static, create an object of the class in your form, and use that object to call the method.



Related Topics



Leave a reply



Submit