'new' and constructors

Sometimes, we might want to create an object AND specify values for its instance variables, e.g:
nameField = new TextField(40);  // initial width
t= new Turtle(0,100);     //  x, y  pos
We do this by defining a method within the class, of the same name as the class. It initialises instance variables.

 class Turtle...  {
     private int x = 200, y = 200;
	 //etc...
	 
	 public Turtle(int initX, int initY) {
	     x = initX;
              y = initY; // copy parameters to instance vars
	 }
	 
	 public void goForward(...){
	 ...
	 }
	 // etc...
}
 
Example of use, from outside the Turtle class:
 private Turtle a,b,c;
 ...
 a = new Turtle(3,3);
 b = new Turtle(100, 200);
 c = new Turtle();  //NO - we MUST use the constructor !!
 
Note:

Overloading method names

A class can have several methods(or constructors )with the same name.

They must have differing parameter types, to enable them to be distinguished.

Benefit: no need for artificially-different names for similar tasks.

Example: we are happy with the default x, y - but want to specify the state of the pen on creation of a turtle:

 class Turtle ...{
     private int x=100, y=100;
	 
	 // two constructors:
	 public Turtle(int initX, int initY){
	     //  as before
	 }
	 
	 public Turtle(boolean penState){
	     penUp = penState;
     }
	 ...etc
 }
 
 
if we put:
 t = new Turtle(true);
 
then Java uses the constructor which has one boolean parameter.

Overloaded methods- example

Imagine we have a BankAccount class - one method is likely to be - withdraw.

We might want to withdraw a standard amount, or a specified amount - so we micht have:

class BankAccount {
    private int balance=0;
	//...constructors here...
	
	//now the methods:
	public void withdraw(){
	    balance=balance-50;
	}
	public void withdraw(int amount){
	    balance=balance-amount;
	}
	...
}
 
We DON'T need to invent two different names, such as withdrawFixed, withdrawAny.