June 8, 2008

Chapter: Operators

Exercise 5: (2) Create a class called Dog containing two Strings: name and says. In main( ), create two dog objects with names “spot” (who says, “Ruff!”) and “scruffy” (who says, “Wurf!”). Then display their names and what they say.

In Java:
public class Dog {

String name, says;

public Dog(String name, String says) {
this.name = name;
this.says = says;

public static void main(String[] args) {
Dog spot = new Dog("spot", "Ruff!");
Dog scruffy = new Dog("scruffy", "Wurf!");
System.out.println(spot.name + ": " + spot.says);
System.out.println(scruffy.name + ": " + scruffy.says);


In Python:
class Dog:
def __init__(self, name, says):
self.name = name
self.says = says

spot = Dog("spot", "Ruff!")
scruffy = Dog("scruffy", "Wurf!")
print(spot.name, spot.says)
print(scruffy.name, scruffy.says)

In Lisp:
(defclass Dog ()
((name :accessor name :initarg :name)
(says :accessor says :initarg :says)))

(setf spot (make-instance 'Dog :name "spot" :says "Ruff!"))
(setf scruffy (make-instance 'Dog :name "scruffy" :says "Wurf!"))
(print (list (name spot)
(says spot)
(name scruffy)
(says scruffy)))