I am confused about composition in java. I am able to write code using inheritance...but have no idea how to turn it into composition...from what my textbook said the two are quite similar has a is a relationship and all.
I ultimately would like to write the cylinder code using composition...but I just dont think i get how to apply the syntax.
public class Circle
{
private double radius;
public Circle(){}
public Circle(double radius)
{
this.radius = radius;
}
public void setRadius(double radius)
{
this.radius = radius;
}
public double findArea()
{
return radius*radius*3.14;
}
public double findPerimeter()
{
return (radius*2)*3.14;
}
}
public class Cylinder extends Circle
{
private double length = 1;
public double getLength()
{
return length;
}
public void setLength(double length)
{
this.length = length;
}
public double findCylinderArea()
{
return (findArea()* 2) + (findPerimeter()*length);
}
public double findVolume()
{
return findArea() * length;
}
}
I also have a test class...
public class TestCircle extends Circle
{
public static void main(String[] args)
{
TestCircle tc1 = new TestCircle();
tc1.setRadius(3);
System.out.println("Circle Perimeter = "+tc1.findPerimeter());
System.out.println("Circle Area = "+tc1.findArea());
Cylinder c1 = new Cylinder();
c1.setRadius(3);
c1.setLength(8);
System.out.println("\nCylinder Area = "+ c1.findCylinderArea());
System.out.println("Cylinder Volume = "+ c1.findVolume());
}
}