iMadz iMadz - 6 months ago 27
Java Question

Constructor and non-static method error

I am having some trouble with the "non-static method cannot be referenced from static context". I know that I should create an instance. But the problem is that in the class I have a constructor which takes a parameter. And When I want to create my instance, I cannot give the needed parameter because I cannot have access to it. How do I solve this problem?
Here is an example so I make myself clear:

public class Trial {

public static void main(String[] args) {

Bloblo t = new Bloblo(2345);
Blabla ts = new Blabla("Imad");
ts.run();
}
}

public class Bloblo {
private int port;
public Bloblo(int leport)
{
port = leport;
System.out.println("au debut le port est: " + port);
}
public void afficher(String nom)
{
System.out.println("on va afficher dans BLOBLO: " + nom + "\net le port est: "+ port);

}
}

public class Blabla implements Runnable{

String Name = "";

public Blabla(String nom)
{
Name = nom;
}

public void run()
{
System.out.println("voici le nom: " + Name);
Bloblo obj = new Bloblo();
obj.afficher(Name);
}
}


The idea here is that i cannot create the instance obj because I have to give port as parameter and I don't know what port it is.

Answer

You should pass the reference to your BloBlo into the BlaBla constructor and store it in a field.

public class Trial {

  public static void main(String[] args) {

            Bloblo t = new Bloblo(2345);
            Blabla ts = new Blabla("Imad", t);
            ts.run();
          }
}

public class Bloblo {
        private int port;
        public Bloblo(int leport)
        {
            port = leport;
            System.out.println("au debut le port est: " + port);
        }
        public void afficher(String nom)
        {
            System.out.println("on va afficher dans BLOBLO: " + nom + "\net le port est: "+ port);

        }
}

public class Blabla implements Runnable{

        String Name = "";
        Bloblo bloblo;
        public Blabla(String nom, Bloblo b)
        {
            Name = nom;
            bloblo = b;
        }

        public void run()
        {
            System.out.println("voici le nom: " + Name);

            bloblo.afficher(Name);
        }
 }