problem with constructor

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jinnejeevansai
    New Member
    • Nov 2014
    • 48

    problem with constructor

    I was not understanding what is going on the output of below code is 0 0.But i was expecting it to be 45 12.Can someone explain the reason for such output.


    Code:
    import java.util.*;
    import java.io.*;
    import java.lang.*;
    class person{
    static int pn,py;
    }
    class patient extends person{
    public patient()
    {
    pn=45;
    py=12;
    }
    static void fun()
    {
    System.out.println(""+pn+py);
    }
    public static void main(String args[])
    {
    fun();
    }
    }
    Last edited by Rabbit; Aug 15 '15, 05:28 PM. Reason: Please use [code] and [/code] tags when posting code or formatted data.
  • Mator
    New Member
    • Aug 2015
    • 3

    #2
    You first have to instantiate your patient class
    The assignment is made in the constructor of the patient class is it not?

    Code:
    import java.util.*;
    import java.io.*;
    import java.lang.*;
    
    class person{
        static int pn;
        static int py;
    }
    
    class patient extends person{
    public patient(){
        person.pn = 45;
        person.py = 12;
    }//end of patient constructor
    
    static void fun(){
        System.out.println("" + person.pn + patient.py);
    }//end of fun()
    
    public static void main(String args[]){
        patient pat = new patient();
        fun();
    }
    }//end of patient class
    You also don't need to import java.lang (always implicitly imported by the JVM)
    Last edited by Mator; Aug 15 '15, 08:50 AM. Reason: Added code sample

    Comment

    • jinnejeevansai
      New Member
      • Nov 2014
      • 48

      #3
      could you explain what you said

      Comment

      • Mator
        New Member
        • Aug 2015
        • 3

        #4
        I have added code samples to make it clearer.

        Comment

        Working...