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 files Cat.java
.
Cat
has three fields, name
, age
and friend
. Each field has a type, which ensures that we can only store a String
in name
, an int
in age
and another Cat
in friend
. The word private
before each field indicates that the field can only be accessed from within the class Cat
.
name
) can be accessed simply by calling name
or {this.name}}. 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 two constructors {{public Cat(String name, int age){...} }}, {{public Cat(String name, int age, Cat friend){...} }}. Constructors are used to create instances of the class. Notice that:
CatsTheMusical.java
.this
to set the variables name
and age
. The arguments of the constructor create variables with the same name as the the fields of the class, shadowing the fields. By using the keyword this
, we can access methods and fields associated with the current instance of the class (being built in the constructor). This pattern, while a little confusing, is conventional.Cat
has two methods, getName(){...
} and sayHello(...){..
}. The first is an example of a getter method. Note that while there is a getter method, there is no setter method, so once a Cat is created, the name cannot be changed.Now that we have the basic terminology down, lets examine some of the finer points:
Here, we included a method getName()
in class Cat
.