Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Cloak
visiblefalse
idCat Code Explained

First, lets talk about the contents of the files Cat.java.

  • Fields: The class 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.
  • Constructors: The class Cat has one constructor public Cat(String name, int age){...}. In the constructor, the fields name and age are initialized with the values given in the arguments, while friend is simply set to null. Because the constructor is public, it can be invoked from other classes. An example of the invoking the constructor can be seen in CatsTheMusical.java.
  • Methods: The class Cat has four methods, getName(){...}, getFriend(){...}, setFriend(Cat friend){...} and sayHello(String aboutMe){...}. The keyword public indicates that the methods can be called outside of the class Cat. The second word in each method is the return type, or the type of the result of the method. Notice that setFriend(...) has a return type of void, indicating that nothing is returned. The first two methods are examples of getter methods, as they simply retrieve the value of a private field. The third method is a setter method, which allows the field friend to be changed from outside the class Cat.

Now lets talk about the other file CatsTheMusical.java.

Now that we have the basic terminology down, lets examine some of the finer points which may be confusing to non-Java programmers:

  • Within a constructor, we can directly access the fields of a class by name without reference to any particular instance, as it is implied that the instance is the one that is being built. For example, in the Cat constructor, we make the assignment friend = null. However, when there are argument variables with the same name as the field variables, they take precedence and shadow the fields variables. To reference the fields once they have been shadowed, you need to use the keyword this. In fact, you can use the keyword this whenever you want to refer to a field or method of the instance of the class being built by the constructor, regardless of whether there is shadowing. The same rules when you are inside a non-static method instead of inside a constructor.
  • In static methods, we cannot refer to any non-static fields or non static methods of the class without also providing an instance, as static methods are not associated with any instance. Similarly, the keyword this cannot be applied.

Now we can discussyou are ready for some more advanced Java!

Inheritance, Abstract Classes, and Inner Classes

...