Quick Index
Problem Statement


Imagination


Use your imagination to code up any three classes. Except do not use our example classes: Point, Square, Rectangle, Person, Planet.

Variables (Three Types)


Each class should declare and use one or more:


The method parameters and local variables should be included in instance methods or constructors (not static methods)

Call Other Instance Methods


Additionally, one or more of your instance methods should call another instance method (in the same class)

Solutions


Below are three example solutions.

  • Instance variable declarations
  • Method parameter declarations
  • Local variable declarations
public class Square {

	private int side;

	public Square(int aSide) {
		this.side = aSide;
	}

	public void setSide(int aSide) {
		this.side = aSide;
	}

	public int computeArea() {
		int ss;
		int area;
		ss = this.side;
		area = ss * ss;
		return area;
	}

	public String toString() {
		return "Square side=" + this.side
			+ " area=" + this.computeArea();
	}

}
  • Instance variable declarations
  • Method parameter declarations
  • Local variable declarations
//Start Person
public class Person {

	private String firstName;
	private String lastName;

	public Person(String aFirstName, String aLastName) {
		this.firstName = aFirstName;
		this.lastName = aLastName;
	}

	public void setNames(String aFirstName, String aLastName) {
		this.firstName = aFirstName;
		this.lastName = aFirstName;
	}

	public String getFullName() {
		String fullName;
		fullName = this.firstName + " " + lastName;
		return fullName;
	}

	public String toString() {
		return "Person: " + this.getFullName();
	}

}
  • Instance variable declarations
  • Method parameter declarations
  • Local variable declarations
public class Planet {

	private String name;
	private int radius;		//miles

	public Planet(String aName, int aRadius) {
		this.name = aName;
		this.radius = aRadius;
	}

	public void setName(String aName) {
		this.name = aName;
	}

	public void setRadius(int aRadius) {
		this.radius = aRadius;
	}

	public int computeCircumference() {
		//Compute distance around the planet
		//Note: Hardcoding PI (3.1416) to simplify example
		double result;
		int rounded;
		//2 * PI * r
		result = 2 * 3.1416 * this.radius;
		//convert to int by calling another method
		rounded = round(result);
		return rounded;
	}

	public int round(double num) {
		//round num to integer
		//e.g. 5.1 -> 5
		//e.g. 5.7 -> 6
		return (int)Math.round(num);
	}

	public String toString() {
		String units = " miles";
		int r, c;
		String rString, cString, fullString;
		r = this.radius;
		c = this.computeCircumference();
		rString = " -- radius = " + r + units;
		cString = " -- circumference = " + c + units;
		fullString = "Planet" + rString + cString;
		return fullString;
	}

}