Object classObject, that every other class is a direct
or indirect subclass of
extends clause, implicitly you are
saying extends Object
Object already contains default definitions for all these,
which will be inherited
toString: the true storyprint and println automatically call toString
toString because...
Object includes a toString method, which will
be inherited
toString simply causes the reference
('pointer') to be printed
Dog:
public String toString() {
return name + " is a " + age + " year old " + breed;
}
== compares references ('pointers')
equals
equals because...
Object includes an equals method, which will
be inherited
equals simply compares 'pointers'
(i.e. it does the same as ==)
Doog:
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (obj == null || getClass() != obj.getClass()) {
return false;
}
Dog d = (Dog) obj;
return (name.equals(d.name) && age == d.age && breed.equals(d.breed));
}
| Primitive types | Reference types |
|---|---|
| Examples | |
int, double, boolean |
arrays, String, Scanner, Dog |
| Contents | |
| Contains a value | Contains null or a reference ('pointer') to an object |
System.out.println(...) | |
| Displays the value | Runs toString
|
| Assignment | |
| Copies the value | Copies the reference (hence two pointers to the same object) |
| Equality testing | |
== tests for equal values |
|
| Passing a parameter to a method | |
| Copies the value, so changes made in the method do not affect the original | Copies the reference (hence two pointers to the same object), so changes to the object made in the method do affect the original |
Object
Objects:
Object[] a = new Object[4];
a[0] = new Dog("Charles", 2, "Charlywawa");
a[1] = new Dog("Colin", 7, "Colombian Drug Lord");
a[2] = new Cow();
int and the other primitive types
into these data structures because they are not objects
Integer,
Double and Boolean – to turn primitives
into objects:
a[3] = new Integer(25);
a[3] = 25;
Objects but that we have
only been inserting LibraryBooks into the array, e.g.:
Object[] library = new Object[1000]; library[0] = new LibraryBook(...); library[1] = new LibraryBook(...); library[2] = new LibraryBook(...); // etc.
LibraryBooks so the only
objects we can 'take out' of the array are LibraryBooks,
but Java won't trust us
LibraryBook b = library[0]; // error here b.acquire();nor with this:
Object b = library[0]; b.acquire(); // error here
LibraryBoook) in the variable b,
we must cast:
LibraryBook b = (LibraryBook) library[0]; b.acquire();Or to persuade it that it is OK to apply one of
LibraryBooks
methods, we must cast:
Object b = library[0]; ((LibraryBook) b).acquire();
LibraryBook
equals
earlierLibraryBooks?
(We lied to the compiler)
Object[] library = new Object[1000]; library[0] = new LibraryBook(...); library[1] = new LibraryBook(...); library[2] = new Cow( ); LibraryBook b = (LibraryBook) library[2]; b.acquire();