Re: instance of a class in a static context??
dendeezen wrote:
How can I create an instance of a class in a static context?
I am a newbie, please point me the right direction.
My code looks like:
public Class1 {
Not a very good class name. java.lang.Class already exists, and your class is
not similar to it.
Try a name like "Example1".
You forgot the keyword 'class'.
// instance of another class
Class2 c2; //[3]
public Class1(Class2 c2) {
this.c2 = c2; //[2]
<code>
}
public static void main(String[] args, Class2 c2) {
This is not the signature for main(). The "real" main() only has one
argument. You will not be able to run this class from the command line.
Go ahead and create a test instance of Example2 inside your main() method
instead of trying to pass it in.
//The next line is not allowed, I know , but what is
the solution?
this.c2 = c2; //[1]
That's because 'this' doesn't exist in a static context. You have to create
an instance of Example1.
Class1 c1 = new Class1(c2);
<code>
c1.setVisible(true);
Now do not write GUI code at this stage, it only complicates things. There is
no 'setVisible()' because there is no GUI, so it will fail to compile.
You have to create an instance of the class to reference anything not static.
********
class Example2
{
public String getName()
{
return "example 2";
}
}
public class Example1
{
private Example2 eg;
public Example1( Example2 e2 )
{
this.eg = e2;
}
public final Example2 getEg()
{
return eg;
}
public static void main( String [] args )
{
Example2 e2 = new Example2();
Example1 e1 = new Example1( e2 );
System.out.println( "Example1 has an Example2 named \""+
e1.getEg().getName() +"\"." );
}
}
--
Lew