Java - a demonstration of inheritance on just one page
Archive - Originally posted on "The Horse's Mouth" - 2008-02-26 23:15:20 - Graham EllisHere's a challenge, just given to me by my Java Delegates, to put my complete example of a Rectangle and a a Circle class, both inheriting from a Shape base class, and a test harness ... on on a single screen. A bit tight, and a bit uncommented, but here it is!
public class Circle extends Shape {
int w;
public Circle (String col,int w) {
super(col); this.w = w; }
public int getarea () {
return (int)(w * w * 0.25 * 3.14159265); } }
// ---------------------------
public class Rectangle extends Shape {
int w; int h;
public Rectangle (String col,int w, int h) {
super(col); this.w = w; this.h = h; }
public int getarea () {
return h * w; } }
// ---------------------------
public class Shape {
private String colour; private static int nshapes = 0;
public Shape(String colour) {
this.colour = colour; nshapes ++; }
public String getcolour() {
return colour; }
public static int getcount() {
return nshapes; } }
// ---------------------------
public class Tablemats {
public static void main (String [] args) {
Rectangle Salisbury = new Rectangle("Orange",30,20);
Circle Bath = new Circle("Purple",25);
String scol = Salisbury.getcolour();
int sarea = Salisbury.getarea(); String bcol = Bath.getcolour();
int barea = Bath.getarea(); int nmats = Shape.getcount();
System.out.println(scol); System.out.println(sarea);
System.out.println(bcol); System.out.println(barea);
System.out.println(nmats); } }
Now - they have to come up with two types of animals - Pets and Farm Animals - where a pet has a specified value and a farm animal has a value PER KILO.