get the Object with "main"

G

Guest

class MainClass {
static public int main(String[] args) {
MainClass a = new MainClass(); // <-- here!
OtherClass b = new OtherClass();
}
..................
}


class OtherClass {
private void aMethod() {
MainClass f = getMainObject(); // <-- and here!
}
}
-----------------------------------------

Can you implement "getMainObject()" to return the "a"?
(a instanceof MainClass)


thanks
 
O

Oscar kind

class MainClass {
static public int main(String[] args) {
MainClass a = new MainClass(); // <-- here!
OtherClass b = new OtherClass();
}
..................
}


class OtherClass {
private void aMethod() {
MainClass f = getMainObject(); // <-- and here!
}
}

No. But this is not necessary: it is always MainClass. Static methods are
always associated with the class in which they are defined, and not with a
subclass.

Just as non-static methods are always associated with the instance of the
class they are defined in, regardless of the (sub)class of the instance.
 
T

Tor Iver Wilhelmsen

MainClass a = new MainClass(); // <-- here!

This is a method-local variable.
OtherClass b = new OtherClass();
class OtherClass {
private void aMethod() {
MainClass f = getMainObject(); // <-- and here!
}
Can you implement "getMainObject()" to return the "a"?
(a instanceof MainClass)

You really should not copy assignemt text verbatim, it becomes too
obvious it's homework.

Hint: You need to pass a to b somehow.
 
M

Matt Humphrey

class MainClass {
static public int main(String[] args) {
MainClass a = new MainClass(); // <-- here!
OtherClass b = new OtherClass();
}
..................
}


class OtherClass {
private void aMethod() {
MainClass f = getMainObject(); // <-- and here!
}
}

No. There is no information in OtherClass that ever contains the reference
to the same object referred to by "a". Somewhere, you must make the
reference what is referred to by "a" available to the OtherClass. Some
options are:

1) Pass MainClass reference in to the OtherClass constructor.

2) Make a static variable in MainClass that is accessible to OtherClass,

3) Create a singleton class that is shared between MainClass and OtherClass
to hold the shared value.

The only way to know which of these (if any) or others is best is to know
exactly what problem you're trying to solve.

Cheers,
Matt Humphrey (e-mail address removed) http://www.iviz.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top