// CS 2510 Spring 2011 // Assignment 3 // Mobiles.java import tester.*; /* Sample mobiles: Simple | 10 blue Complex | | | ------------+----- | | ------+------ | | | | 10 | 40 red 10 green blue */ /* Class Diagram +---------+ | IMobile |<---------------+ +----x----+ | / \ | +---+ | | | +-------------------+ | | | | +--------------+ +---------------+ | | Simple | | Complex | | +--------------+ +---------------+ | | int length | | int length | | | int weight | | int leftside | | | String color | | int rightside | | +--------------+ | IMobile left |---+ | IMobile right |--/ +---------------+ */ // Represents a Hanging Mobile interface IMobile{ // Count the number of weights in this Mobile int countWeights(); } // to represent an item hanging at the end of a mobile class Simple implements IMobile { int length; int weight; String color; Simple(int length, int weight, String color) { this.length = length; this.weight = weight; this.color = color; } /* Template: Fields: ... this.length ... -- int ... this.weight ... -- int ... this.color ... -- String Methods: ... this.countWeights() ... -- int */ // Count the number of weights in this Simple Mobile int countWeights(){ return 1; } } // Represents a complex structure of a Mobile class Complex implements IMobile { int length; int leftSide; int rightSide; IMobile left; IMobile right; Complex(int length, int leftSide, int rightSide, IMobile left, IMobile right){ this.length = length; this.leftSide = leftSide; this.rightSide = rightSide; this.left = left; this.right = right; } /* Template: Fields: ... this.length ... -- int ... this.leftside ... -- int ... this.rightside ... -- int ... this.left ... -- IMobile ... this.right ... -- IMobile Methods: ... this.countWeights() ... -- int Methods for Fields: ... this.left.countWeights() ... -- int ... this.right.countWeights() ... -- int */ // Count the number of weights in this Complex Mobile int countWeights(){ return this.left.countWeights() + this.right.countWeights(); } } // Tests for Mobiles class MobileExamples{ MobileExamples(){} IMobile simp1 = new Simple(2, 10, "blue"); IMobile simp2 = new Simple(3, 40, "green"); IMobile simp3 = new Simple(1, 10, "red"); IMobile comp1 = new Complex(1, 6, 6, this.simp3, this.simp1); IMobile comp2 = new Complex(3, 12, 5, this.comp1, this.simp2); // Tests for countWeights boolean testCountWeights(Tester t){ return (t.checkExpect(simp1.countWeights(), 1) && t.checkExpect(comp1.countWeights(), 2) && t.checkExpect(comp2.countWeights(), 3)); } }