July 28, 2008

Chapter: Holding Your Objects

Create a new class called Gerbil with an int gerbilNumber that's initialized in the constructor. Give it a method called hop() that displays which gerbil number this is, and that it's hopping. Create an ArrayList and add Gerbil objects to the List. Now use the get() method to move through the List and call hop() for each Gerbil.


As we proceed deeper into the book, completing the exercises using multiple languages exposes the differences more clearly. In my opinion Lisp and Java are completely different beasts, with Python combining Lisp's ease of programming with Java-like syntax.

In Java:
package chapter.holdingYourObjects;

import java.util.*;

class Gerbil {
private int gerbilNumber;

Gerbil(int gerbilNumber) {
this.gerbilNumber = gerbilNumber;
}

public void hop() {
System.out.println("Gerbil " + gerbilNumber + " is hopping");
}
}

public class Exercise1 {
public static void main(String[] args) {
ArrayList<Gerbil> gerbils = new ArrayList<Gerbil>();
for(int i = 0; i < 10; i++)
gerbils.add(new Gerbil(i));

for(int i = 0; i < gerbils.size(); i++)
gerbils.get(i).hop();
}
}


In Python:
class Gerbil:
def __init__(self, gerbilNumber):
self.gerbilNumber = gerbilNumber
def hop(self):
print "Gerbil " + str(self.gerbilNumber) + " is hopping"

gerbils = []
for i in range(10):
gerbils.append(Gerbil(i))

for i in range(len(gerbils)):
gerbils[i].hop()


In Lisp:
(defclass Gerbil ()
((gerbil-number :accessor gerbil-number
:initarg :num)))

(defmethod hop ((g Gerbil))
(format t "Gerbil ~d is hopping~%" (gerbil-number g)))

(defparameter *gerbil-list*
(loop for i from 0 to 9 append
(list (make-instance 'Gerbil :num i))))

(loop for a-gerbil in *gerbil-list* do (hop a-gerbil))

July 27, 2008

at Sunday, July 27, 2008 Labels: , Posted by Billy 0 comments

While I was working on a Spring application, I saw the following error after deploying:

org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 1 in XML document from ServletContext resource [/WEB-INF/BCC-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException: White spaces are required between publicId and systemId.



Here are the first few lines of the xml file the stack trace was referring to:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-2.0.xsd
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">


The report stateed the error was in Line 1, which was obviously not the case. The problem was the order of the schemaLocation values was incorrect. Here is the correct order:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">

July 10, 2008

Chapter: Inner Classes

Create an interface U with three methods. Create a class A with a method that produces a reference to a U by building an anonymous inner class. Create a second class B that contains an array of U. B should have one method that accepts and stores a reference to a U in the array, a second method that sets a reference in the array (specified by the method argument) to null, and a third method that moves through the array and calls the methods in U. In main(), create a group of A objects and a single B. Fill the B with U references produced by the A objects. Use the B to call back into all the A objects. Remove some of the U references from the B.



I also added a couple lines of code to show that A's inner class has access to it's private methods.

package chapter.innerClasses;

interface U {
void one();
void two();
void three();
}

class A {
U getU() {
return new U() {
public void one() {System.out.println("one");}
public void two() {System.out.println("two");}
public void three() {System.out.println("three"); printSomething();}
};
}

private void printSomething() {System.out.println("Something");}
}

class B {
private U[] arrayOfU = new U[10];
private int position = 0;

public void storeU(U U_Reference) {
if (position < 10 && position >= 0)
arrayOfU[position++] = U_Reference;
}

public void setNull(int index) {
if (index < 10 && index >= 0)
arrayOfU[index] = null;
}

public void callU() {
for (U myU : arrayOfU) {
if (myU != null) {
myU.one();
myU.two();
myU.three();
}
}
}
}

public class Excercise23 {
public static void main(String[] args) {
A firstA = new A(), secondA = new A();
B theB = new B();
theB.storeU(firstA.getU());
theB.storeU(secondA.getU());
theB.storeU(secondA.getU());
theB.callU();
theB.setNull(1);
theB.callU();
}
}

July 7, 2008

Chapter: Interfaces

Create a framework using Factory Methods that performs both coin tossing and dice tossing.


In Java:
package chapter.interfaces;

import java.util.*;

interface Game {
int toss();
}

interface GameFactory {
Game getGame();
}

class Dice implements Game {
public int toss() {
Random rand = new Random(55);
return rand.nextInt(7);
}
}

class DiceFactory implements GameFactory {
public Game getGame() {
return new Dice();
}
}

class Coins implements Game {
public int toss() {
Random rand = new Random(55);
return rand.nextInt(3);
}
}

class CoinsFactory implements GameFactory {
public Game getGame() {
return new Coins();
}
}

public class Exercise19 {

public static void playGame(GameFactory factory) {
Game game = factory.getGame();
for (int i = 0; i < 8; i++)
System.out.println(game.toss());
}

public static void main(String[] args) {
playGame(new CoinsFactory());
playGame(new DiceFactory());
}

}

Chapter: Interfaces

Create three interfaces, each with two methods. Inherit a new interface that combines the three, adding a new method. Create a class by implementing the new interface and also inheriting from a concrete class. Now write four methods, each of which takes one of the four interfaces as an argument. In main(), create an object of your class and pass it to each of the methods.


In Java:
package chapter.interfaces;

interface A {
void a1();
void a2();
}

interface B {
void b1();
void b2();
}

interface C {
void c1();
void c2();
}

interface D extends A, B, C {
void d1();
}

class E {
public void e1() {System.out.println("e1");}
}

class F extends E implements A, B, C, D {
public void a1() {System.out.println("a1");}
public void a2() {System.out.println("a2");}
public void b1() {System.out.println("b1");}
public void b2() {System.out.println("b2");}
public void c1() {System.out.println("c1");}
public void c2() {System.out.println("c2");}
public void d1() {System.out.println("d1");}
}



public class Exercise14 {
public static void foo(A a) {
a.a1();
a.a2();
}
public static void bar(B b) {
b.b1();
b.b2();
}
public static void yen(C c) {
c.c1();
c.c2();
}
public static void zen(D d) {
d.a1();
d.a2();
d.b1();
d.b2();
d.c1();
d.c2();
d.d1();
}
public static void main(String[] args) {
F f = new F();
foo(f);
bar(f);
yen(f);
zen(f);
f.e1();


}

}

Chapter: Interfaces

Create an interface, and inherit two new interfaces from that interface. Multiply inherit a third interface from the second two.


In Java:
package chapter.interfaces;

interface AI {
void top();
}

interface BI extends AI {
void left();
}

interface CI extends AI {
void right();
}

interface DI extends CI, BI {
void bottom();
}

class EC implements DI {
public void top() {System.out.println("Top");}
public void left() {System.out.println("Left");}
public void right() {System.out.println("Right");}
public void bottom() {System.out.println("Bottom");}
}

public class Exercise13 {
public static void main(String[] args) {
EC e = new EC();
e.top();
e.left();
e.right();
e.bottom();
}
}

at Monday, July 07, 2008 Posted by Billy 0 comments

Chapter: Interfaces

Create an abstract class with no methods. Derive a class and add a method. create a static method that takes a reference to the base class, downcasts it to the derived class, and calls the method.


In Java:
package chapter.interfaces;

abstract class Base {
}

class Sub extends Base {
public void foo() {
System.out.println("Sub foo");
}
}

public class Exercise4 {
private static void bar(Base b) {
((Sub) b).foo();
}

public static void main(String[] args) {
bar(new Sub());
}
}

Chapter: Polymorphism

Create an inheritance hierarchy of Rodent: Mouse, Gerbil, and Hamster. In the base class, provide methods that are common to all Rodents, and override these in the derived classes to perform different behaviors depending on the specific type of Rodent. Create an array of Rodent, fill it with different types of Rodents, and call your base class methods to see what happens.


In Java:
package chapter.polymorphism;

class Rodent {
public void play() {
System.out.println("Rodent playing");
}
public void eat() {
System.out.println("Rodent eating");
}
}

class Mouse extends Rodent {
public void play() {
System.out.println("Mouse playing");
}
public void eat() {
System.out.println("Mouse eating");
}
}

class Gerbil extends Rodent {
public void play() {
System.out.println("Gerbil playing");
}
public void eat() {
System.out.println("Gerbil eating");
}
}

class Hamster extends Rodent {
public void play() {
System.out.println("Hamster playing");
}
public void eat() {
System.out.println("Hamster eating");
}
}

public class Exercise9 {
public static void main(String[] args) {
Rodent[] rodents = { new Rodent(), new Mouse(), new Gerbil(),
new Hamster() };

for (Rodent rodent : rodents) {
rodent.play();
rodent.eat();
}
}
}


In Python:
class Rodent:
def play(self): print 'Rodent playing'
def eat(self): print 'Rodent eating'

class Mouse(Rodent):
def play(self): print 'Mouse playing'
def eat(self): print 'Mouse eating'

class Gerbil(Rodent):
def play(self): print 'Gerbil playing'
def eat(self): print 'Gerbil eating'

class Hamster(Rodent):
def play(self): print 'Hamster playing'
def eat(self): print 'Hamster eating'

rodents = (Rodent(), Mouse(), Gerbil(), Hamster())
for rodent in rodents:
rodent.play()
rodent.eat()

Chapter: Reusing Classes

Create a class called Amphibian. From this, inherit a class called Frog. Put appropriate methods in the base class. In main(), create a Frog and upcast it to Amphibian and demonstrate that all the methods will work.


In Java:
package chapter.reusingClasses;

class Amphibian {

private void move() {
System.out.println("Moving");
}

private void swim() {
System.out.println("Swimming");
}

static void travel(Amphibian a) {
a.move();
a.swim();
}
}

class Frog extends Amphibian {

}

public class Exercise16 {

public static void main(String[] args) {

Frog kermit = new Frog();

Amphibian.travel(kermit);

}

}


In Python:
class Amphibian:
def move(self):
print "Moving"

def swim(self):
print "Swimming"

def travel(self):
self.move()
self.swim()

class Frog(Amphibian):
pass

frog = Frog()
frog.travel()

Chapter: Reusing Classes

Create two classes, A and B, with default constructors (empty argument lists) that announce themselves. Inherit a new class called C from A, and create a member of class B inside C. Do not create a constructor for C. Create an object of class C and observe the results.


Notice the different output in the two solutions.

In Java:
package chapter.reusingClasses;

class A {
A() {
System.out.println("A");
}
}

class B {
B() {
System.out.println("B");
}
}

class C extends A {
B b = new B();
}

public class Exercise5 {

public static void main(String[] args) {

C c = new C();

}

} /* Output:
A
B
*///


In Python:
class A:
def __init__(self):
print "A"

class B:
def __init__(self):
print "B"

class C(A):
b = B()

C()

# Output:
# B
# A

Chapter: Initialization and Cleanup

Create an array of String objects and assing a String to each element. Print the array by using a for loop


I also demonstrate an alternative way to print the array.

In Java:
package chapter.initialization;

import java.util.*;

public class Exercise16 {

public static void main(String[] args) {

String[] stringArray = new String[] { "aaa", "bbb", "ccc", "ddd" };

for (String x : stringArray)
System.out.println(x);

System.out.println(Arrays.toString(stringArray));
}
}


In Python:
stringArray = ("aaa", "bbb", "ccc", "ddd")

for x in stringArray:
print x

print stringArray


In Lisp:
(setq string-array '("aaa" "bbb" "ccc" "ddd"))

(loop for x in string-array do (print x))

(print string-array)