0

I have read from a website that instance variables can be accessed directly within the class but my code below works only with object. can someone please help.Thanks in advance!

public class InstanceVariable
    {
        int instVariable;
        // Instance variable are accessed through objects
        public static void main(String []args)
        {
            /* Local variables has no default value but Instance variables 
            can have default value */
    
            int a = 10;
            // Here local variables a cannot have access modifiers
            InstanceVariable obj = new InstanceVariable();
            System.out.println(obj.instVariable);
            System.out.println(a);
        }
    }
3
  • You will have to define variable instVariable as static in order to access it without the help of object in the main method Commented Jul 17, 2022 at 6:33
  • 1
    Your question is one of the basic aspects of object oriented languages. If you struggle at this point, then I forsee you having lots of other similar questions in near future. Instead of asking here, I'd highly suggest you to grab a book about any object oriented language and go through it. It'll explain such core concepts much better than SO can. Commented Jul 17, 2022 at 6:34
  • This site is not for tutorials on the basics of Java. Study the extensive Java Tutorials provided free of cost by Oracle. Read the new 2022 edition of Head First Java. Commented Jul 17, 2022 at 6:45

0

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.