Classes and Objects: Track the number of objects

Question: Create a class which keeps track of the number of its objects

package Ch9;

/**
 * Q: Create a class which keeps track of the number of its objects
 * Created by aarushi on 16/6/21.
 */
public class ChEx06 {

    //values of static variables are same across all instances of the class
    static int numberOfObjects=0;
    //values of instance variables are different for each object
    int num;

    public ChEx06(int num){
        numberOfObjects++;
        this.num= num;
    }

    //static methods do not require an object to be accessed
    //static methods cannot access instance variables
    public static int getNumberOfObjects(){
        return numberOfObjects;
    }

    //instance methods can be used only with objects of the class
    public int getNum(){
        return num;
    }

    /*
    Sample Output:
    Number of objects: 1
    Number of objects: 4
    Values of num:
    Object 1: 3
    Object 2: 56
    Object 3: 100
    Object 4: 2
     */
}
package Ch9;

/**
 * Created by aarushi on 16/6/21.
 */
public class ChEx06Test {
    public static void main (String[] args){
        ChEx06 obj1= new ChEx06(3);
        System.out.println("Number of objects: " + ChEx06.getNumberOfObjects());
        ChEx06 obj2= new ChEx06(56);
        ChEx06 obj3= new ChEx06(100);
        ChEx06 obj4= new ChEx06(2);
        System.out.println("Number of objects: " + ChEx06.getNumberOfObjects());
        System.out.println("Values of num: ");
        System.out.println("Object 1: " + obj1.getNum());
        System.out.println("Object 2: " + obj2.getNum());
        System.out.println("Object 3: " + obj3.getNum());
        System.out.println("Object 4: " + obj4.getNum());
    }
}

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: