In Java, all code is associated with a class. Classes have fields and methods. Here is an example of two simple classes:
|
Lets make sure we understand how this works. First, lets talk about the contents of the file Cat.java
.
Cat
has two fields, name
and age
. Each field has a type, which ensures that we can only store a String
in name
and an int
in age. The word private
before each field indicates that the field can only be accessed from within the class Cat
. In Java, by convention most fields are private, and if you want to be able to access them from outside the class, you add getter and setter methods (we will get to these shortly).Cat
has a single constructor public Cat(String name, int age){...
}. Constructors are used to create instances of the class. An example of the invoking the constructor can be seen in CatsTheMusical.java
. Here, we included a method getName()
in class Cat
.