삼성SDS_멀티캠퍼스/Java

11일 차 다형성

박성우기 2015. 9. 21. 10:29
반응형


class Shape {


protected int x, y;


public int getX() {

return x;

}


public void setX(int x) {

this.x = x;

}


public int getY() {

return y;

}


public void setY(int y) {

this.y = y;

}


@Override

public String toString() {

return "Shape [x=" + x + ", y=" + y + "]";

}


public Shape() {


}


public void draw() {


System.out.println("Shape draw");

}


};


class Rectangle extends Shape {

private int height, width;

public int getHeight() {
return height;
}

public void setHeight(int height) {
this.height = height;
}

public int getWidth() {
return width;
}

public void setWidth(int width) {
this.width = width;
}

@Override
public String toString() {
return "Rectangle [height=" + height + ", width=" + width + "]";
}

public Rectangle() {
// TODO Auto-generated constructor stub
}

public Rectangle(int height, int width) {
super();
this.height = height;
this.width = width;
}

public void draw() {
System.out.println("Rectangle draw");

}
}

class Triangle extends Shape {

private int base, height;

public int getBase() {
return base;
}

public void setBase(int base) {
this.base = base;
}

public int getHeight() {
return height;
}

public void setHeight(int height) {
this.height = height;
}

@Override
public String toString() {
return "Triangle [base=" + base + ", height=" + height + "]";
}

public Triangle() {

}

public Triangle(int base, int height) {
super();
this.base = base;
this.height = height;
}

public void draw() {
System.out.println("Triangle draw");

}

};

class Circle extends Shape {

private int radius;

public int getRadius() {
return radius;
}

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

@Override
public String toString() {
return "Circle [radius=" + radius + "]";
}

public Circle() {

}

public Circle(int radius) {
super();
this.radius = radius;
}

public void draw() {
System.out.println("Circle draw");

}

};

class Cylinder extends Shape {

public void draw() {
System.out.println("Cylinder draw");
}
}

public class ShapeTest {

private static Shape arrayOfShapes[];

public static void main(String[] args) {
// TODO Auto-generated method stub
init();
drawAll();

}

public static void init() {
arrayOfShapes = new Shape[4];
arrayOfShapes[0] = new Rectangle();
arrayOfShapes[1] = new Triangle();
arrayOfShapes[2] = new Circle();
arrayOfShapes[3] = new Cylinder();
}

public static void drawAll() {

for (int i = 0; i < arrayOfShapes.length; i++) {
arrayOfShapes[i].draw();
}
}

};





















반응형