Question

Discuss the difference between an "instance member variable" and a "static member variable" Give an example...

Discuss the difference between an "instance member variable" and a "static member variable" Give an example to support your answer.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
Instance Variables hold values that must be referenced essential parts of an object's state. Instance Variables are created for every object of class.
It is not shared by all the objects of class.
Instance Variables are accessed by objects of class.

Static Variable would only be one copy of each class variable per class, regardless of how many objects are created from it
It is shared by all the objects of class.
To access Static Variable we do not need any object. We just use class name to access it.

Example:
//TestCode.java
public  class TestCode {
    public int instanceVariable;
    public static int staticVariable = 0;

    public TestCode(int instanceVariable) {
        this.instanceVariable = instanceVariable;
        staticVariable += 1;
    }

    public static void main(String[] args) {
        TestCode t1 = new TestCode(5);
        System.out.println("t1.instanceVariable = "+t1.instanceVariable);
        System.out.println("TestCode.staticVariable = "+TestCode.staticVariable);

        TestCode t2 = new TestCode(10);
        System.out.println("t2.instanceVariable = "+t2.instanceVariable);
        System.out.println("TestCode.staticVariable = "+TestCode.staticVariable);
    }
}

Add a comment
Know the answer?
Add Answer to:
Discuss the difference between an "instance member variable" and a "static member variable" Give an example...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT