By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,473 Members | 3,229 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,473 IT Pros & Developers. It's quick & easy.

problem with constructor

P: 48
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.


Expand|Select|Wrap|Line Numbers
  1. import java.util.*;
  2. import java.io.*;
  3. import java.lang.*;
  4. class person{
  5. static int pn,py;
  6. }
  7. class patient extends person{
  8. public patient()
  9. {
  10. pn=45;
  11. py=12;
  12. }
  13. static void fun()
  14. {
  15. System.out.println(""+pn+py);
  16. }
  17. public static void main(String args[])
  18. {
  19. fun();
  20. }
  21. }
Aug 15 '15 #1

✓ answered by Mator

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

Expand|Select|Wrap|Line Numbers
  1. import java.util.*;
  2. import java.io.*;
  3. import java.lang.*;
  4.  
  5. class person{
  6.     static int pn;
  7.     static int py;
  8. }
  9.  
  10. class patient extends person{
  11. public patient(){
  12.     person.pn = 45;
  13.     person.py = 12;
  14. }//end of patient constructor
  15.  
  16. static void fun(){
  17.     System.out.println("" + person.pn + patient.py);
  18. }//end of fun()
  19.  
  20. public static void main(String args[]){
  21.     patient pat = new patient();
  22.     fun();
  23. }
  24. }//end of patient class
  25.  
  26.  
  27.  
You also don't need to import java.lang (always implicitly imported by the JVM)

Share this Question
Share on Google+
3 Replies


P: 3
You first have to instantiate your patient class
The assignment is made in the constructor of the patient class is it not?

Expand|Select|Wrap|Line Numbers
  1. import java.util.*;
  2. import java.io.*;
  3. import java.lang.*;
  4.  
  5. class person{
  6.     static int pn;
  7.     static int py;
  8. }
  9.  
  10. class patient extends person{
  11. public patient(){
  12.     person.pn = 45;
  13.     person.py = 12;
  14. }//end of patient constructor
  15.  
  16. static void fun(){
  17.     System.out.println("" + person.pn + patient.py);
  18. }//end of fun()
  19.  
  20. public static void main(String args[]){
  21.     patient pat = new patient();
  22.     fun();
  23. }
  24. }//end of patient class
  25.  
  26.  
  27.  
You also don't need to import java.lang (always implicitly imported by the JVM)
Aug 15 '15 #2

P: 48
could you explain what you said
Aug 15 '15 #3

P: 3
I have added code samples to make it clearer.
Aug 15 '15 #4

Post your reply

Sign in to post your reply or Sign up for a free account.