Lecture 11: More Inheritance

Overview

  1. Recap from Wednesday
  2. Activity: Abstract Shapes
  3. Class Hierarchies
  4. Object class

Recap of Last Time

  • Introduced object inheritance
    • define one class as a subclass of another
    • only implement the differences between the classes
    • use keyword extends

Also Last Time

  • Introduced abstract classes
    • like a normal class, but some methods are abstract
    • abstract methods are not implemented, only declared
    • subclasses must implement abstract methods though
  • Instances of abstract classes cannot be created

Abstract Shapes

public abstract class BouncingShape {
    public static final int DEFAULT_WIDTH = 25;
    public static final int DEFAULT_HEIGHT = 25;    
    
    protected Pair curPosition;      // position of the center
    protected Pair curVelocity;      // disk velocity (px / sec)
    protected Pair nextPosition;     // position in next frame
    protected Pair nextVelocity;     // velocity in next frame    
    protected double width;
    protected double height;
    protected Color color;
    protected World world;           // the world to which the disk belongs
    
    public BouncingShape(World world, double width, double height, Color color, Pair position, Pair velocity) {
	this.world = world;
	this.width = width;
	this.height = height;
	this.color = color;
	curPosition = new Pair(position);
	curVelocity = new Pair(velocity);
	nextPosition = new Pair(position);
	nextVelocity = new Pair(velocity);
    }

    public void update (double time) {
	Pair delta = curVelocity.times(time);
        nextPosition.set(curPosition.plus(delta));
        bounce();
    }

    public void advance () {
	curPosition.set(nextPosition);
	curVelocity.set(nextVelocity);
    }

    public void setPosition(Pair p){
        curPosition.set(p);
    }

    public void setVelocity(Pair v){
        curVelocity.set(v);
    }

    public abstract void draw(Graphics g);

    protected void bounce() {
	
        if (nextPosition.getX() - width / 2 <= 0){
            nextVelocity.flipX();
            nextPosition.setX(width / 2);
        } else if (nextPosition.getX() + width / 2 >= world.getWidth()){
            nextVelocity.flipX();
            nextPosition.setX(world.getWidth() - width / 2);
        }
	
        if (nextPosition.getY() - height / 2 <= 0){
            nextVelocity.flipY();
            nextPosition.setY(height / 2);
        } else if (nextPosition.getY() + height / 2 >=  world.getHeight()) {
            nextVelocity.flipY();
            nextPosition.setY(world.getHeight() - height / 2);
        }
    }
}

Activity

Write subclasses for BouncingShape to draw different shapes!

  • disk
  • square
  • diamond

Test Your BouncingShapes