Chapter 2 A Trip to Objectville
1.Thinking about Objects
Things an object knows about itself are
instance variables.
Things an object can do are
methods.
2.Making objects
Use two classes to create and use an object. One for the type of object you want to use, and another class to test the new class.
1)Write the class:
public class Dog
{
int size;
String breed;
String name;
void bark()
{
System.out.println("Ruff");
}
}
2)Write the class test drive:
public class DogTestDrive
{
public static void main(String[] args)
{
Dog d = new Dog();
d.size = 40;
d.bark();
}
}
3.Get out of main
The two uses of main: to test the real class and to launch/start the java application
Exercise :
A.We should new a TapeDeck t before we give it values.
class TapeDeck {
boolean canRecord = false;
void playTape() {
System.out.println("tape playing");
}
void recordTape() {
System.out.println("tape recording");
}
}
class TapeDeckTestDrive {
public static void main (String[] args){
TapeDeck t = new TapeDeck();
t.canRecord = true ;
t.playTape();
if (t.canRecord == true) {
t.recordTape();
}
}
}
B.the example didn't define a playDVD method.
class DVDplayer {
boolean canRecord = false;
void playDVD() {
System.out.println("DVD playing");
}
void recordDVD() {
System.out.println("DVD recording");
}
}
class TapeDeckTestDrive {
public static void main (String[] args){
DVDplayer d = new DVDplayer();
d.canRecord = true ;
d.playDVD();
if (d.canRecord == true) {
d.recordDVD();
}
}
}