The constructor and the new-expression

The constructor and the new-expression - Constructors...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Constructors Here’s class Chapter , with three fields, the chapter number, chapter title, and the previous chapter. Here is an instance of that class, created using an assignment c= new Chapter(); . The only way to initialize the fields of the new instance is through calls on the setter methods, for example: c.setNumber(1); c.setTitle("Intro"); c.setPrev( null ); If we had more fields —and many classes will have 5 or 10 or even more— it would become more laborious and awkward to initialize the fields. We need a simpler way to initialize fields of an new object. Java lets us indicate the initialization in the new-expression itself. Instead of having to create the instance and then initialize the fields, we will be able to do it like this —the 1 is the value for field number   and the string is the value for field title . c= new Chapter(1, "Intro"); We won’t have to initialize field prev because that is initialized to a default value of null , anyway. But this doesn’t work yet!. Before it will work, we have to write a new kind of method, called a constructor . Here’s how we do it. First, write a specification:
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 07/07/2008 for the course CS 101 taught by Professor Gries during the Spring '08 term at Cornell University (Engineering School).

Page1 / 2

The constructor and the new-expression - Constructors...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online