jkigel
jkigel

Reputation: 1592

Java call method in Main class

Let's say I have Main class, and it has an instance of class A.

How can I call a method in Main class within class A ?

Thanks!

Upvotes: 0

Views: 5615

Answers (5)

edwga
edwga

Reputation: 190

If the method is a static method (i.e. was declared with "public static ReturnType methodName()") then in the A class, you need to call Main.methodName().

However, if the method is an instance method (declared as "public ReturnType methodName()") then you need to somehow pass an instance of Main into the instance of A (perhaps through the constructor, or a setter method). Inside the A class, you could then call instanceOfMain.methodName().

However (as some people have already mentioned) this is probably not the best way to handle things. The Main class should simply be where the program starts; it is not where you should be doing any real program logic.

Upvotes: 0

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

This is called Composition...Where a class has a Reference of other class...

Composition is preferred over Inheritance when we need one or few functionalities But Not all the functionalities of a class.

Eg:

public class A{

 Main m = new M();  // m is a Object Reference Variable of type Main in class A
 m.go();           // go() is a method in class Main

 }

Upvotes: 1

Android Killer
Android Killer

Reputation: 18489

To call a method in Main class from calss A you need an instance of Main class within the class A(considering them in same package) if both the calsses have no relation like inheritance.if static then you may call Main.methodName();

Upvotes: 0

Bholzer
Bholzer

Reputation: 189

Main.methodName() for a static method.

Though it sounds to me like what you're trying to do may be bad practice. Your Main method or class should simply be an entry point

Upvotes: 0

Dhruv Gairola
Dhruv Gairola

Reputation: 9182

If it is an instance method, then you need an instance of M inside A to call M's method inside A. If it is a static method, you can just call it directly. But you're holding circular references so beware.

Upvotes: 0

Related Questions