declaring fields and getter setter methods

declaring fields and getter setter methods - Field...

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

View Full Document Right Arrow Icon
Field declarations and getter/setter methods Consider writing a class Chapter . Each instance of Chapter will contain information about a chapter of a book, like the chapter number, so we need to declare a variable in the class. The basic form of a declaration of this variable, as you know, is int number , but we put a semicolon after it: int number; // The chapter number. This is what an object of class Chapter now looks like —yes, it is initialized to the default value 0. A variable declared in a class definition is called a field or instance variable , because it is appears in every instance of the class. And, you can see that we can create an instance of the class, assign a value to the field, and tobtain the value: x= new Chapter(); x.number= 3; x.number Access modifiers for fields Generally, we give an access modifier in the declaration. Access modifier public allows access to the field from any place in which the instance is accessible. Instead, we use access modifier private , which signifies that the field is accessible only from code within class Chapter . Here, we’ll show you. Compile the program, create an instance of it, as before, and then try to assign field
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.

Page1 / 2

declaring fields and getter setter methods - Field...

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