Interfaces in Java.

import java.awt.*;
import java.util.*;

public class WeightedTest {

    public static void main(String [] args) {
	Vector v = new Vector();

	// adding new elements:
	WeightedRectangle wr = new WeightedRectangle();
	wr.setBounds(100, 50, 10, 30);
	v.add(wr);
	
	wr = new WeightedRectangle();
	wr.setBounds(100, 0, 5, 60);
	v.add(wr);

	wr = new WeightedRectangle();
	wr.setBounds(30, 40, 50, 50);
	v.add(wr);

	Weighted w = max(v);
	System.out.println("the max is: " + w);

	WeightedPoint wp = new WeightedPoint();
	wp.setLocation(10000, 10000);
	v.add(wp);

	w = max(v);
	System.out.println("the max is: " + w);
	
    }

    public static Weighted max(Vector v) {
	Weighted w = (Weighted) v.get(0);
	for (int i = 1; i < v.size(); ++i) {
	    if (w.weight() < ((Weighted) v.get(i)).weight())
		w = (Weighted) v.get(i);
	}
	return w;
    }
}


class WeightedRectangle extends Rectangle implements Weighted {
    public double weight() {
	return height * width;
    }
}

class WeightedPoint extends Point implements Weighted {
    public double weight() {
	return Math.sqrt(x * x + y * y);
    }
}

interface Weighted {
    public double weight();
}


This is an example from CSci 1211 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.