What is a class?
In Java, all code is associated with a class. Classes have fields and methods. Here is an example of two simple classes:
Cat.java
public class Cat{
private int age;
private String name;
public Cat(String name, int age){
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public String sayHello(){
return "Hello World! My name is " + name
+ " and I am " + age + " years old.";
}
}
CatsTheMusical.java
public class CatsTheMusical{
public static void main(String[] args){
Cat mist = new Cat("Mr. Mistoffelees",8);
System.out.println(mist.sayHello);
}
}
Lets make sure we understand how this works. First, lets talk about the contents of the file Cat.java.
- Fields: The class
Cathas two fields,nameandage. Each field has a type, which ensures that we can only store aStringinnameand anintin age. The wordprivatebefore each field indicates that the field can only be accessed from within the classCat. 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). - Constructors: The class
Cathas a single constructor {{public Cat(String name, int age)Unknown macro: {...}}}. Constructors are used to create instances of the class. An example of the invoking the constructor can be seen inCatsTheMusical.java. - Methods:
Here, we included a method getName() in class Cat.