See Below.
Here is the constructor.
This constructor creates two objects by
using their constructors.
References to the new objects are copied into the corresponding instance variables of the new Tree
.
The int
variables are initialized in the usual way.
A toString()
method has been added.
The height of the tree is the height of the trunk plus the height of the branches.
Include additional attributes in the toString()
method if you wish.
// Tree.java // public class Tree { // instance variables private double x, y, z; private Cone branches; private Cylinder trunk; // constructor public Tree( double trRad, double trHeight, double brRad, double brHeight, double x, double y, double z) { trunk = new Cylinder( trRad, trHeight ); branches = new Cone( brRad, brHeight ); this.x = x; this.y = y; this.z = z; } // methods public String toString() { double totalHeight = branches.getHeight() + trunk.getHeight(); double width = branches.getRadius(); return "Tree. Height: " + totalHeight + ", width: " + width ; } // more methods to come ... }
A wise programmer tests early and often. Here is a testing class:
// TreeTester.java // public class TreeTester { public static void main( String[] args ) { double trunkR = 1.0, trunkH = 5.0, branchR = 25.0, branchH = 50.0 ; Tree myTree = new Tree( trunkR, trunkH, branchR, branchH, 1, 2, 3 ); System.out.println("myTree: " + myTree + "\n"); } }
When you compile TreeTester.java
the compiler will also compile
Tree.java
,
Cone.java
, and
Cylinder.java
if they in the same directory and need to be compiled.
When TreeTester.class
is run,
the run-time system will use the class files when needed.
C:\JSource> javac TreeTester.java C:\JSource> dir Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 9/1/2017 11:32 PM 1179 Cone.class -a---- 9/1/2017 11:25 PM 936 Cone.java -a---- 8/30/2017 7:15 PM 741 Cylinder.class -a---- 8/29/2017 8:26 PM 884 Cylinder.java -a---- 9/22/2019 12:04 PM 1073 Tree.class -a---- 9/22/2019 12:03 PM 693 Tree.java -a---- 9/22/2019 12:20 PM 981 TreeTester.class -a---- 9/22/2019 12:03 PM 314 TreeTester.java
The program prints out:
C:\JSource> java TreeTester myTree: Tree. Height: 55.0, width: 25.0
Here is a picture of a BlueJ version of the same code: BlueJ Tree
What is the volume of the tree?