0

A nonstatic variable can be accessed through the static main method by creating an object of that class. how is this possible?

the object-oriented rule is non-static variable can not be accessed by static method because While we run a class, first static blocks/ static variable initialization happens. Static block gets executed when a class is loaded into JVM. so we can't access nonstatic variable inside executed static method. But why only this scenario no compilation error? please give me a explanation

This is allowed

 public class Thread1 extends Thread{   
        int s ;
    }
        public class MainThread {
        int y =89;
            public static void main(String[] args)  {
            Thread1 j = new Thread1();
            System.out.println(j.s=43);
            }

        }

This is not allowed why ???

public class MainThread {
int y =89;
    public static void main(String[] args)  {

    Thread1 j = new Thread1();
    System.out.println(y);
    }

}

Thanks :)

B_Ali_Code
  • 65
  • 10
  • Focus on [this answer](https://stackoverflow.com/a/2559596/522444) in the duplicate. – Hovercraft Full Of Eels Dec 03 '17 at 17:22
  • 1
    *This is not allowed why ???* Because `y` is not static, and you are trying to access it from a static context (the `main` method is static). – BackSlash Dec 03 '17 at 17:24
  • You'd need `static int y = 89` – OneCricketeer Dec 03 '17 at 17:33
  • @BackSlash I agree with your point but that not the case for me.i know non-static can not b accessed through static field.. but my question is inside static main method access the non-static variable is allowed by creating class object .. check ma code thanks – B_Ali_Code Dec 03 '17 at 17:37
  • @B_Ali_Code It's because you are accessing it through an instance. In the second example you have no instance of class `MainThread` – BackSlash Dec 03 '17 at 17:39

0 Answers0