Java Reference
In-Depth Information
//************************
// method showDogData()
//************************
public void showDogData()
{
System.out.println("My name is " + this.dogName);
System.out.println("I am dog number " + this.dogNum);
}
}
//***********************************
//***********************************
// CLASS VirtualDog
//***********************************
//***********************************
public class VirtualDog
{
public static void main(String[] args)
{
// Declare objects of class Dog
Dog dog1 = new Dog();
// First object is named dog1
Dog dog2 = new Dog();
// Second object is dog2
// Assign names to Dog objects using setName() method
dog1.setDogData(1, "Fido");
// dog1 name
dog2.setDogData(2, "Maverik");
// dog2 name
// Call methods of the class Dog using objects
dog1.bark();
// dog1 barks
dog1.showDogData();
// dog1 says its name and
// number
dog2.showDogData();
// ... and so on
dog2.bark();
}
}
Object instantiation
The program VirtualDog.java. listed previously, contains two classes. The
classVirtualDogiscalledthe driving class .EveryJavaprogrammustcon-
tain a driving class. The method main() must be in the driving class. The
otherclassintheprogramisDog.Dogisa helper class .TheclassDogcon-
tains two attributes, defined as follows:
// Class variables
private int dogNum; // Dog object number
private String dogName; // Dog object name
Note that the object attributes are defined at the class level, that is,
outside the methods. They are defined with the private qualifier so that
they are not visible outside the class. Private attributes preserve encapsu-
Search WWH ::




Custom Search