This is a Java Program to Demonstrate Usage of an Instance Variable x in the Test Class.
Here we made a variable X as an instance variable and if we try to access that from main() directly then it will show error and it proves that all non – static things of a class always belong to an object. Thus, keep those properties of an object as an instance whose values are changing from each instance of an object.
Here is the source code of the Java Program to Demonstrate Usage of an Instance Variable x in the Test Class. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
public class Test
{
int x = 17;
public static void main(String...a)
{
//System.out.println(x); Error : non-static variable x cannot be referenced from a static context
// non static variable can be called only after making objects
Test ob = new Test();
System.out.println(ob.x);
}
}
Output:
$ javac Test.java $ java Test 17
Sanfoundry Global Education & Learning Series – 1000 Java Programs.
advertisement
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Check Programming Books
- Check Java Books
- Practice Programming MCQs
- Apply for Java Internship
- Practice BCA MCQs