-1

I want to get the value of my variable sub in method and pass it on my Constructor

// this is my method

private int sub;
public void getSubj (int sub) {
   this.sub = sub;
}

// and this my constructor

public schedule (int sub) {
    subject = sub;
    System.out.print(subject);
}
Michaël
  • 3,679
  • 7
  • 39
  • 64
Orville
  • 518
  • 7
  • 17
  • The constructor get executed during construction and never again for a certain object. So you cannot pass an argument to the constructor of the same object. – Gábor Bakos Dec 17 '14 at 08:35
  • Just pass the value to the constructor and that value will be stored in "sub" variable. The method will be available to call, after you have created the object using your constructor. – tharindu_DG Dec 17 '14 at 08:42
  • im just wondering what use case are you doing why you do it that way. – Ryan Dec 17 '14 at 08:43
  • go through this : http://stackoverflow.com/questions/19061599/methods-vs-constructors-in-java – tharindu_DG Dec 17 '14 at 08:44

2 Answers2

1

Methods call after the constructor finished. You cannot call any method of class, before calling its constructor.

You can still call methods inside the constructor.

public schedule (int sub) {
    subject = sub;
    System.out.print(subject);
    getSubj(sub);
}
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • Plus one. I know what you're saying but you might want to expand on calling methods *within* a constructor. – Bathsheba Dec 17 '14 at 08:35
  • @sᴜʀᴇsʜ ᴀᴛᴛᴀ, but your example shows calling constructor inside method, right? – Yazan Dec 17 '14 at 08:41
1

Your question doesn't make much sense.

When you call a constructor, you are passing it data from outside the instance being created with this constructor.

The method getSubj looks like a setter (despite its name). It is another way to update the state of the object after the constructor is called, but it's not passing anything to the constructor, since it can't be called before the constructor is executed (unless the constructor calls it, in which case the constructor would be passing data to it and not the other way).

You code would make more sense this way:

private int sub;
public void setSubj (int sub) // renamed from getSubj, since it's a setter
{
    this.sub = sub;
}

public schedule (int sub) 
{
    this.sub = sub;
}

public static void main (String[] args)
{
    schedule s = new schedule (10); // invoke the constructor
    s.setSubj(20); // invoke the setter method to change the state of the instance
}
Eran
  • 387,369
  • 54
  • 702
  • 768