Constructors


The compiler is complaining that it cannot find an appropriate Student constructor. A constructor looks a lot like a method. It can contain any number of statements and can take any number of arguments like a method. However, you must always name a constructor the same as the class in which it is defined. Also, you never provide a return value for a constructor, not even void. You use a constructor to allow an object to be initialized, often by using other objects that are passed along as arguments to the constructor.

In the example, you want to be able to pass along a student name when you instantiate, or construct, a Student object. The code

 new Student("Jane Doe"); 

implies that there must be a constructor defined in the Student class that takes a single parameter of the String type. You can define such a constructor by editing Student.java so that it looks like this:

 class Student {    Student(String name) {    } } 

Compile again and rerun your JUnit tests:

 javac -classpath c:\junit3.8.1\junit.jar *.java java -cp .;c:\junit3.8.1\junit.jar junit.awtui.TestRunner StudentTest 

You should see a green bar.

The constructor currently doesn't do anything with the name String passed to it. It is lost in the ether! Soon, you'll modify the Student class definition to hold on to the name.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net