Welcome

Welcome to my blog.


I will be updating this blog with lecture notes and miscellaneous information for:

CSE 1030 : Winter Term
Prof. A. Eckford, Section-Z: MWF at 10:30 in R S137



Feel free to leave me a message or send me an e-mail at producap@yorku.ca.

Here is a link for MyMail, Hotmail, G-mail, and PRISM login.

On that note, you must have a PRISM account in order to write the lab tests.

If you have not created a PRISM account yet (e.g., if you received transfer credit for 1020), see the lab monitor in CSEB 1006 as soon as possible.

I will also leave the blog open to comments, etc. much like the CSE forums.

Thanks for visiting.

Phil.

Monday, January 21, 2008

CSE Lecture 21/Jan/2007

Object Copying

-to copy non-objects, all we do is e.g.

int x =5;
int y;
y = x;

-is this the right way to copy an object?

BankAccount b = new BankAccount(100)
BankAccount c;
c = b;

c is not a copy, it is a reference to the same object.

You must:

1) create a new object
2) initialize it with the same state as the original.
e.g. double x = b.getBalance();
BankAccount c = new BankAccount(x);

Better Solution: The Copy Constructor

-Takes only one parameter -> the object to be copied.
BankAccount b = new BankAccount(100);
BankAccount c = new BankAccount(b); //create a copy of b

public BankAccount(BankAccount original)
{

//assign all attributes of this to be equal to attributes of original
balance = original.balance;

}

-It is the class's responsibility to provide a copy constructor.

-Sometimes there is a method called clone()
-only to be used if no alternative exists
-never write classes containing clone(), always use the copy constructor.

Mutable vs. Immutable classes

Mutable
-attributes can be changed after the object is constructed.

Immutable
-attributes cannot be changed after construction.

Immutable classes have no method to modify attributes, but provide access method to get the attributes.

If you can show that your class is immutable, you don't need a copy constructor.

ImmutableClass i = new ImmutableClass(5);
ImmutableClass j = i; //this is fine

Mutable classes require copy constructors.

No comments: