0% found this document useful (0 votes)
4 views

Exercise JAVA

Exercise JAVA, Java OOP

Uploaded by

nhattunguyen1412
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Exercise JAVA

Exercise JAVA, Java OOP

Uploaded by

nhattunguyen1412
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

SAKAI => ASSIGMENTS => INHERITANCE

1, 2, 3
Exercise 1: The Circle and Cylinder Classes
The class Cylinder inherits all the member variables (radius and color) and methods
(getRadius(), getArea(), among others) from its superclass Circle. It further defines
a variable called height, two public methods - getHeight() and getVolume() and its
own constructors

Circle.java (Re-produced)

public class Circle {


// private instance variables

// Constructors

// public getters and setters for the private variables

/** Returns a self-descriptive String */


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

/** Returns the area of this Circle */


public double getArea() {
return radius * radius * Math.PI;
}
}

Cylinder.java
/**
* A Cylinder is a Circle plus a height.
*/
public class Cylinder extends Circle {
// private instance variable

// Constructors

// Getter and Setter

/** Returns the volume of this Cylinder */


public double getVolume() {
return getArea()*height; // Use Circle's getArea()
}

/** Returns a self-descriptive String */


public String toString() {
return "This is a Cylinder"; // to be refined later
}
}
A Test Drive for the Cylinder Class (TestCylinder.java)
/**
* A test driver for the Cylinder class.
*/
public class TestCylinder {
public static void main(String[] args) {
Cylinder cy1 = new Cylinder();
//Construced a Circle with Circle()
//Constructed a Cylinder with Cylinder()
System.out.println("Radius is " + cy1.getRadius()
+ ", Height is " + cy1.getHeight()
+ ", Color is " + cy1.getColor()
+ ", Base area is " + cy1.getArea()
+ ", Volume is " + cy1.getVolume());
//Radius is 1.0, Height is 1.0, Color is red,
//Base area is 3.141592653589793, Volume is 3.141592653589793

Cylinder cy2 = new Cylinder(5.0, 2.0);


//Construced a Circle with Circle(radius)
//Constructed a Cylinder with Cylinder(height, radius)
System.out.println("Radius is " + cy2.getRadius()
+ ", Height is " + cy2.getHeight()
+ ", Color is " + cy2.getColor()
+ ", Base area is " + cy2.getArea()
+ ", Volume is " + cy2.getVolume());
//Radius is 2.0, Height is 5.0, Color is red,
//Base area is 12.566370614359172, Volume is 62.83185307179586
}
}

You might also like