CS335 (Fall 2008)
Solution of Homework 3 (20 points)
Due: 9/23/08
(4 points)
1. 1) s.length() // for String s
2) a[i].length // for array a[][]
3) a.length // for array a[][]
4) a.length // for array a[]
(4 points)
2. 1) True.
2) False. Array space is not allocated in the declaration but by
using the "new" operator.
3) False. Strings are constants.
(A String object is called immutable (read-only) because its value
cannot be modified once it has been created. Methods that appear
to modify a String object actually return a new String object
that contains the modification.)
4) False. A static method cannot access non-static variables or
non-static methods directly. It must use an object reference.
Also, a static method cannot use the "this" keyword as there
is no instance for "this" to refer to.
(2 points)
3. The code compiles and executes. But the constructor is no longer
treated as a constructor, but a method (will not be called when
an object is instantiated).
(4 points)
4. You don't get the extra lines because whenever you say something
like
blah = blarg;
all you really do is set the blah pointer to be equal to the blarg
pointer; you don't copy the data. When you then set circle1 to
null that POINTER is set to NULL but since you still have two other
pointers (namely, pointref and circle2) pointing to the same data
then the garbage collector doesn't destroy it as it's still in use.
If you set pointref and circle2 to NULL then nothing is pointing
to the object anymore and the garbage collector will call
finalize() on it.
(6 points)
5. The class defined using composition instead of inheritance is
shown below.
In this case, using composition seems to makes more sense because a
"base plus commission employee" is not really a "commission employee",
but with the characteristic of a "commission employee". Therefore,
the "is-a" relationship is not as strong as the "has-a" relationship.
////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////
public class BasePlusCommissionEmployee4
{
private double baseSalary;
private CommissionEmployee3 e;
public BasePlusCommissionEmployee4( String first, String last,
String ssn, double sales, double rate, double salary )
{
CommissionEmployee3 e =
new CommissionEmployee3( first, last, ssn, sales, rate );
setBaseSalary( salary );
}
public void setBaseSalary( double salary )
{
baseSalary = ( salary < 0.0 ) ? 0.0 : salary ;
}
public double getBaseSalary( )
{
return baseSalary;
}
public double earnings( )
{
return getBaseSalary() + e.earnings();
}
public String toString( )
{
return String.format( "%s %n%s: %.2f", "base-salaried",
e.toString( ), "base salary", getBaseSalary( ) );
}
}
////////////////////////////////////////////////////////////////////