Static variables can be called without object creation

This is how the math functions and constants work.

// jamesprogram.java
class jamesprogram {

	public static void main (String[] args){
		
		cat member1 = new cat("Emma", "Smith");
		cat member2 = new cat("Larry", "Oldman");
		cat member3 = new cat("Bob", "Timpy");
		
		System.out.println();
		System.out.println(member1.getFirst());
		System.out.println(member1.getLast());
		System.out.println(member1.getMembers());
		
		System.out.println();
		System.out.println(member2.getFirst());
		System.out.println(member2.getLast());
		System.out.println(member2.getMembers());
		
		// since static variables don't change
		// between objects, static information is
		// available even when you don't have an
		// object
		System.out.println();
		// we don't need to create an object because
		// the variable would be the same anyway
		// cus it's static, so the below displays
		// the number of members in the cat class
		System.out.println(cat.getMembers());
		
	}
}
//cat.java
public class cat {
	
	private String first;
	private String last;
	// every object SHARES the same variable,
	// if you change a static variable, you change
	// it for ALL objects
	private static int members = 0;
	
	// constructor
	public cat (String fn, String ln){
		first=fn;
		last=ln;
		members++;
		System.out.printf("Constructor for %s %s, members in the club: %d\n", first, last, members);
	}
	
	// method to return first name
	public String getFirst(){
		return first;
	}
	
	// method to return last name
	public String getLast(){
		return last;
	}
	
	// method to return the members
	// we have to use 'static int' because
	// this is the 'type' that the variable
	// was declared as
	public static int getMembers(){
		return members;
	}
	
}

Outputs:

Constructor for Emma Smith, members in the club: 1
Constructor for Larry Oldman, members in the club: 2
Constructor for Bob Timpy, members in the club: 3

Emma
Smith
3

Larry
Oldman
3

3

Leave a Reply