Write a complete Java program illustrating the difference between instance and static members of class. Indicate with comments where each is used and explain the significance of making the instance or static. (6 marks)
/*
Static variables are associated with a class and are called
directly using the class name. Instance variables are associated
with an object and must be called by the name of the object.
Static data members are used in classes in cases
where some data needs to be used independently of
any declared object of that class.
When both instances are used directly in the object to edit it, and so on.
*/
class Test{
public static String testStat; // static members of class
public String test; // instance members of class
}
public class Main {
public static void main(String[] args) {
Test test = new Test();
Test.testStat = "Static"; // Static class members are called like this
test.test = "instances"; // and instances are called like this (Class object cannot call static class member)
}
}
Comments
Leave a comment