Studyon Minte9.com
Fundamentals (Docs)

Study

Objects



Object creation

As you know, a class provides the blueprint for objects; you create an object from a class.

	Point originOne = new Point(23, 94);

Each of these statements has three parts

	- Declaration (Point originOne)
	- Instantiation (The new keyword is a Java operator that creates the object)
	- Initialization (a call to a constructor, which initializes the new object)

Simply declaring a reference variable does not create an object.

	Point originOne;

The reference returned by the new operator can also be used directly in an expression.

	int height = new Rectangle().height;

All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler 
automatically provides a no-argument constructor, called the default constructor. 


Referencing an Object's Fields

Code that is outside the object's class must use an object reference or expression, 
followed by the dot (.) operator, followed by a simple field name.

	objectReference.fieldName = 2;
	objectReference.methodName(argumentList);


The Garbage Collector

An object is eligible for garbage collection when there are no more references to that object. 
References that are held in a variable are usually dropped when the variable goes out of scope.


Using the THIS Keyword

Within an instance method or a constructor, this is a reference to the current object.

	public class Point {
	    public int x = 0;
	    public int y = 0;
	    public Point(int x, int y) {
		this.x = x;
		this.y = y;
	    }
	}

The most common reason for using the this keyword is because a field is shadowed by 
a method or constructor parameter.


Using this with a Constructor

From within a constructor, you can also use the this keyword to call another constructor in the same class.

	public class Rectangle {
	    private int x, y;
	    private int width, height;
		
	    public Rectangle() {
		this(0, 0, 0, 0);
	    }
	    public Rectangle(int width, int height) {
		this(0, 0, width, height);
	    }
	    public Rectangle(int x, int y, int width, int height) {
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
	    }
	}

This class contains a set of constructors. The compiler determines which constructor to call, based on the 
number and the type of arguments.


http://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html