You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

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);
  }
}
  • No labels