2

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"?

1 Answer 1

1
  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

Sign up to request clarification or add additional context in comments.

5 Comments

I don't think in class Iam method Iam is a constructor as the constructor does not possess any return type.
@chandu_reddim - yes correct, I have updated my response.
I know that Java is a strongly typed language so that I thought that it will through an error as we did not initialize static int x. but i didn't get the answer that how we are able to access that static content by an object as object possess only non-static content.
A static variable belongs to the class (this variable is shared by all objects of that class as well, and while it may not belong specifically to them, they can access it). Although you can access it from an instance as you have, the preferred and most common way you will see it is (You.x in your case) or through the class itself directly.
so we can access a class variable or instance variable irrespective of static or non static but it not applies for method am I correct ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.