Menu Close


Java: Classes

What Is a Class?

We often use the word classification: the action or process of classifying something according to shared qualities or characteristics. In the real world, you’ll often find many individual objects all of the same kind.

Java is a pure object-oriented language. The class is the most important aspect of Java language. We use a class to define objects.

So a Java class is a small program that is used as template to generate objects from it. This program is executed and it generate an object.


public class Animal{

  // The Animal class has 2 fields (instance variables)
  private float weight;
  private String name;

  //The Animal class has one constructor
  public Animal(float animalWeight, String animalName) {
    this.weight = animalWeight; = animalName;

  //The Animal class has four methods
  public void setWeight(float weight) {
    this.weight = weight;
  public float getWeight() {
    return weight;

  public void setName(String name) { = name;
  public String getName() {
    return name;

In the previous example we define a class Animal. This class has two private properties: weight and name.

Class constructor

A class has several methods. This is the name of procedures or functions that are defined inside a class. One of the methods is very important and is distinguishing from the others by its name.

The constructor method has its name identical with the class name: Animal. Also this method has several parameters used to initialize the object private properties.

Object instantiation

A class can’t be used until an object is instantiated. This is done using the new keyword into an assignment statement from another class.

class AnimalDemo {
    public static void main(String[] args) {
        Animal dog = new Animal(5,"dog");
        System.out.println("Hello " + dog.getName());


See also:  Oracle Documentation