Java Classes & Objects
The following code demonstrates declaration of a class - Dog
- and its instantiation into objects.
MyProgram.java
package ceccs;
public class MyProgram {
public static void main(String[] args){
System.out.println("The species of the dog is " + Dog.species);
Dog.bark();
Dog myDog = new Dog();
myDog.name = "Jennifur";
myDog.gender = 'f';
myDog.ageYrs = 16;
myDog.breed = "Poodle";
myDog.weight = 120;
Dog yourDog = new Dog();
yourDog.name = "Brover";
yourDog.gender = 'm';
yourDog.breed = "Chihuahua";
yourDog.weight = 7;
yourDog.ageYrs = 100;
System.out.println("My dog's name is " + myDog.name);
System.out.println("Your dog's name is " + yourDog.name);
if(myDog.weight > yourDog.weight) {
System.out.println("My dog is bigger than yours nanananana!");
} else {
System.out.println("Big dogs are over rated.");
}
System.out.println("Your Dog is " + yourDog.ageYrs + " years old.");
System.out.println("In dog years that's " + yourDog.getAgeInDogYears());
System.out.println("My Dog is " + myDog.ageYrs + " years old.");
System.out.println("In dog years that's " + myDog.getAgeInDogYears());
myDog.happyBirthday();
System.out.println("... it's one year later.");
System.out.println("My Dog is " + myDog.ageYrs + " years old.");
System.out.println("In dog years that's " + myDog.getAgeInDogYears());
// Note we don't call happy birthday for yourDog
System.out.println("Your Dog is " + yourDog.ageYrs + " years old.");
System.out.println("In dog years that's " + yourDog.getAgeInDogYears());
}
}
Dog.java
package ceccs;
public class Dog {
//instance variables or instance data
String name;
float weight;
int ageYrs;
String breed;
char gender;
//Static variables belong to the whole class
static String species = "Canis lupus familiaris";
//constructor - called with 'new' to create and initialize a dog
Dog() {
name = "No Name";
weight = 0;
ageYrs = 0;
breed = "No Breed";
gender = 'x';
}
void happyBirthday(){
ageYrs++;
}
int getAgeInDogYears(){
int dogYears;
// large dog?
if (weight > 40) {
dogYears = ageYrs * 8;
} else {
dogYears = ageYrs * 5;
}
return dogYears;
}
static void bark(){
System.out.println("Woof! Woof!");
}
}