...
Section |
---|
|
Column |
---|
| Code Block |
---|
|
public class Cat {
private int age;
private String name;
private Cat friend;
public Cat(String name, int age) {
this.name = name;
this.age = age;
this.friend = null;
}
public String getName() {
return name;
}
public Cat getFriend() {
return friend;
}
public void setFriend(Cat friend) {
this.friend = friend;
}
public String sayHello(String aboutMe) {
return "Hello World! My name is " +
name + " and I am " + age +
" years old." + " I am " + aboutMe + ".";
}
}
|
|
Column |
---|
| Code Block |
---|
|
public class CatsTheMusical {
public static void main(String[] args) {
Cat mist = new Cat("Mr. Mistoffelees", 8);
System.out.println(mist.sayHello("magical"));
Cat garf = new Cat("Garfield", 12);
System.out.println(garf.sayHello("tired/hungry"));
mist.setFriend(garf);
System.out.println(mist.getName() + " and " + garf.getName()
+ " are friends? " + CatsTheMusical.areFriends(mist, garf));
garf.setFriend(mist);
System.out.println(mist.getName() + " and " + garf.getName()
+ " are friends? " + CatsTheMusical.areFriends(mist, garf));
}
public static boolean areFriends(Cat cat1, Cat cat2) {
if (cat1.getFriend() != null && cat2.getFriend() != null) {
return cat1.getFriend() == cat2 && cat2.getFriend() == cat1;
}
return false;
}
}
|
|
|
...
- 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
. - Methods: The class
Cat
has two four methods, getName(){...
}, getFriend(){...
}, setFriend(...){...
} and sayHello(...){..
}. The keyword{{public}} indicates that the methods can be called outside of the class Cat
. 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 changedsecond 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 that we have the basic terminology down, lets examine some of the finer points:
...