![]() |
||||||
![]() |
||||||
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
|
![]() |
![]() |
Anatomy of a Class File files: BouncingTurtle.java (help)
Class comment Lines 1 - 5 are the class comment that should be at the top of every class file. The comment should say a few words about what the class does and how to use it. You may also put other information here such as creation date, author's name and copyright statement. Import statements Lines 6 and 7 contain import statements. These lines specify which other classes or packages (code libraries) your class is going to use. Line 6 says we are going to use the classes in the standard java.awt package and line 7 indicates we will be using classes in the com.otherwise.jurtle package. Class declaration Line 9 contains the class declaration. Specifying the superclass As discussed in Lesson 3: A Bit About Objects, all Java objects are part of an inheritance hierarchy and all ultimately are derived from the class Object. When you declare a class, you must specify which class is its immediate superclass. You do this using the extends keyword, followed by the name of its superclass. Thus, if you were creating the class Dog, you might specify that its superclass is Mammal as follows: Access modifiers What about the word public on line 9 above? This is a modifier that specifies how the class may be used. Modifiers are optional. Here are the basic ones we will be using: |
||
![]() |
![]() |
![]() |
|
|||||||
![]() |
![]() |
![]() |
The class body After the class declaration comes the class body. In BouncingTurtle this is the code from the opening curly brace on line 10 until the closing curly brace on line 51. The class body generally contains declarations of member variables (i.e. instance and static variables) and methods. These declarations must be between the opening and closing curly braces that follow the class declaration. Declaring member variables Member variables are declared within the opening and closing braces of the class body and outside of any method declarations for the class. Typically they are declared as the first thing in the class body, but they don't have to be. Some programmers put all their variable declarations at the end of the class body. |
||
![]() |
![]() |
![]() |
|
|||||||||||
![]() |
![]() |
![]() |
Method declarations We will discuss method declarations in more detail in Lesson 12: Methods - Creation and Use. Here you should just notice that the two methods defined in the BouncingTurtle class, runTurtle() and move(), are declared inside the class body, one after the other. You cannot declare methods outside of the class body (after the final closing curly brace), nor can you declare a method within the body of another method declaration. Exercises Look over some of the Turtle classes in the Examples folder in the directory where Jurtle is installed. Try to identify in these classes the various parts described above.
|
||
![]() |
![]() |
![]() |