The this Keyword
-this refers to the current object
-this is always legal to use, sometimes makes the program easier to read
-can be used to resolve ambiguities in variable scope.
public class MyClass
{
private int x;
.
.
.
public void printX()
{
System.out.println(x); <--- can replace x by this.x
}
public void printOtherX(MyClass m)
{
System.out.println(this.x);
System.out.println(m.x);
}
}
Note: methods in classes have access to all private members of any object of that same class type(just not this).
This() as a method refers to the constructor of the current object.
public class MyClass
{
private int x;
public MyClass(int x)
{ this.x = x}
public MyClass() //default constructor
{this(0);
}
Two Special Methods: equals() and toString()
toString()
-creates a string representation of your object.
-method is called whenever your object is cast to a String
e.g. MyClass m = new MyClass();
System.out.println(m);
Expected style of toString output:
Class Name[attribute=value,attribute=value...]
e.g. public class MyClass
{
private int x;
private double y;
x = 0;
y = 3.5;
public String toString()
{
String s;
s = "MyClass[x=" + x + ", y=" + y + "]";
return s;
}
Should return MyClass[x-0,y=3.5]
equals()
-intended to determine whether two objects are equal.
-the == in e.g. m==n is true whenever m and n are objects if and only if m and n point to the same object.
-because of this we need the equals method.
public boolean equals(Object o)
{
MyClass m = (MyClass) o; //this is called a cast.
if ((x==m.x) && (y==m.y))
{return true;}
else {return false;}
}
Use getClass() method to determine whether the classes are equal.
{ if(this.getClass() == o.getClass())
{
MyClass m = (MyClass) o;
.
.
.
}else{return false}
}
Welcome
Welcome to my blog.
I will be updating this blog with lecture notes and miscellaneous information for:
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
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment