chandu_reddim
chandu_reddim

Reputation: 117

How I am getting static instance variable with object of that class

For info, I am using java 8.

public class You { 
  static int x;
   public static void main(String args[]){
   Iam c= new Iam();
   c.Iam();
     }
}
 class Iam{

   public void  Iam(){

   You c =new You();
   System.out.println(c.x);
   }
}
  1. Question 1: how I am able to get the static class field (class variables /instance variables) from the non-static method of other class by creating an object of a static field that is residing. I know that only non-static content will be in the object then how I am able to get that value?
  2. Question 2: How I am able to create a method with the same name as the class? (I think it is not a constructor as void is added to it)
  3. Question 3: while printing the output is "ZERO" the default constructor is created by JVM as I am not coded any. My question is do the default constructor initializes the class variables to "ZERO"?

Upvotes: 2

Views: 171

Answers (1)

vbn
vbn

Reputation: 274

  1. Please go through basic java documentation on class variables

  2. Method with same name is called constructor of the class, please go through java documentation, java would still allow you to define a method with the same name as ctor with a return type.

  3. Your static variable is primitive, which are always initialized with default values for 'int' its zero

Good starting for learning Java is at Learning the Java Language

Upvotes: 1

Related Questions