Studyon Minte9.com
Head First (Java)




Objects



		// Instance variables / Methods
		// Object creation (3 steps)
		// Reference & Garbage Collection


* Class and objects

	When you design a class, think about the objects that will be created from that class type.

		- Instace variables: 
			Things the object KNOWS 
				(title, artist)
		- Methods: 
			Things the object DOES 
				(setTitle(), setArtist(), play())

	%java

		public class TestingApp {
		    
		    public static void main(String[] args) {
			
			Dog d = new Dog();
			d.size = 40;
			d.bark();
		    }
		}

		class Dog {
		    
		    int size;
		    String name;
		    
		    void bark() {
			System.out.println("Ham Ham");
		    }
		}



* Object creation

	Doq myDoq = new Dog () ;

	1) Declare reference variable

		( Doq myDoq ) ...

	Tells the JVM to allocate space for a reference variable, and names that variable myDog. 
	The reference variable is, forever of type Dog.
	ln other words, a remote control that has buttons to control a Dog, but not a Cat or a Button or a Socket.

	2) Create an object

		... ( new Dog() )

	Tells the JVM to allocate space for a new Dog object on the heap.

	3) Link the object and the reference

		... ( = ) ...


* Reference

	Book b = new Book(); // object 1
	Book c = new Book(); // object 2
		// two Book reference variable
		// two Book objects

	Book d = c;
		// three Book reference variable
		// two Book objects
		// Both c and d refer to the same object

	c = b;
		// the reference of c with object 2 is destroyed 
		// (eligible for Garbage Collection)
		// c is now a reference to object 1

	%java

		public class TestingApp {
		    
		    public static void main(String[] args) {
			
			Book b = new Book(1);
			Book c = new Book(2);
			System.out.println(b.x + "/" + c.x);
			    // Output: 1/2
			
			Book d = c;
			System.out.println(b.x + "/" + c.x + "/" + d.x);
			    // Output: 1/2/2
			    
			c = b;
			    // c is now reference to object 1
			    // c reference to object 2 is destroyed
			System.out.println(b.x + "/" + c.x + "/" + d.x);
			    // Output: 1/1/2
		    }
		}

		class Book {
		    int x = 0;
		    public Book(int x) { // contructor
			this.x = x;
		    }
		}