Free Java Tutorials >> Table of contents >> Classes

1. Fields

What is a class?

The word class is related to "classification","category", or "set". Classes in Java (and many other languages) are your own variable types.

Declaring a class

Typically, classes are defined in separate files. A ".java" file is only allowed one public class, although it can have multiple non-public classes. Additionally, classes declared inside of other classes are called inner classes. You cannot declare classes within functions or methods (the exception being anonymous classes).

See this code that declares a class Cat:

public class MyProgram {
    public static void main(String[] args) {
		Cat garfield = new Cat();     //This creates a new object of type Cat
		System.out.println(garfield); //You can print objects, which will print their memory address by default
    }
}
//This creates the new "Cat" variable type
class Cat { //It is good style to capitalize classes, but this is not required by Java
}

Instantiating Objects of a Class Type

While you might declare an integer with int x = 5, classes are instantiated with the "new" operator. For example Cat x = new Cat(); creates a variable of type Cat with name x.

Fields

A class is like a variable type that contains other variables. The variables within an object are called "Fields". Here, we can add fields to the Cat type:

class Cat {
	int age;     //Each Cat will contain an int, called age
	String name; //Each Cat will contain a String called name
}

Accessing and modifying fields

Once a class has fields, you can modify and access the fields for each object you create:

public class MyProgram {
    public static void main(String[] args) {
		Cat mimi = new Cat();
		mimi.name = "Mimi the fabulous";   //modifying a field
		mimi.age = 2;
		Cat garfield = new Cat();
		garfield.name = "Garfield";
		garfield.age = 42;
		System.out.println(mimi.name);    //Prints "Mimi the fabulous"
		System.out.println(garfield.age); //Prints 42
    }
}
//This creates the new "Cat" variable type
class Cat {
	int age;     //Each Cat will contain an int, called age
	String name; //Each Cat will contain a String called name
}

Even though we declared int age and String name only once in the prior example, every cat has an age and a name. Mimi has an age and a name, and garfield has a different age and name. In other words, by creating the class Cat, we can create these name/page pairs every time we create a cat. We access the name inside of mimi with mimi.name, which we can either modify or print.

Creating an array of Objects

Just like other variable types, you can create an array of class types. However, each index must be initialized using the "new ObjectName()" constructor before you can access its fields:

public class MyProgram {
    public static void main(String[] args) {
		Cat[] kitties = new Cat[3]; //An array that will hold 3 cats
		kitties[0] = new Cat();
		kitties[0].name = "mimi";
		kitties[0].age = 2;
		kitties[1] = new Cat();
		kitties[1].name = "garfield";
		kitties[1].age = 42;
		kitties[2] = new Cat();
		kitties[2].name = "felix";
		kitties[2].age = 2001;

		//we can now output all the kitties:
		for(int i = 0 ; i << kitties.length; i++) { //loop with i equaling 0,1, and 2
		System.out.println(kitties[i].name+" is "+kitties[i].age+" months old");
		}
    }
}
class Cat {
	int age;
	String name;
}

Since kitties[0] is a cat, we can access its fields with kitties[0].name. As you can see, the for loop allows us to iterate over all cats in the array.



			
Run

2. Methods

Creating and using methods

Methods are functions inside of classes, just like fields were variables inside of classes. Let's see our first method:

public class MyProgram {
    public static void main(String[] args) {
		Cat mimi = new Cat();
		mimi.makeSound(); //prints meow!
		Cat garfield = new Cat();
		garfield.makeSound(); //prints meow!
		//you cannot just run makeSound()
    }
}
class Cat {
  int age;
  String name;
  void makeSound() {
    System.out.println("meow!");
  }
}

As you can see, you need an object (class variable) to run a method. Let's see a method that uses fields within, boolean isKitty():

public class MyProgram {
    public static void main(String[] args) {
		Cat mimi = new Cat();
		mimi.age = 2;
		boolean mimiKitty = mimi.isKitty(); //sets mimiKitty to true since age<10 true in mimi
		Cat garfield = new Cat();
		garfield.age = 42;

		System.out.println(mimiKitty); //prints true
		System.out.println(garfield.isKitty()); //prints false  
    }
}
class Cat {
  int age;
  String name;
  void makeSound() { //method not used in this example
    System.out.println("meow!");
  }
  boolean isKitty() {
    return age < 10;
  }
}

Inside of this isKitty method, the variable age is a field. Thus, the variable age is different depending on which Cat we run isKitty on. For mimi, the age was set to 2, so isKitty() returned true. For garfield, age was set to 42 so isKitty() returned false. This allows us to create behaviour that is different depending on which cat we run the method on.



			
Run

3. Constructors

Creating and using constructors

Let's look at how we set fields previously:

public class MyProgram {
    public static void main(String[] args) {
		Cat x = new Cat();
		x.age = 1;       //setting a field
		x.name = "Bob";  //setting another field 
    }
}
class Cat { int age; String name; }

Java provides the ability for us to create a "constructor" to give variables when we create a Cat:

public class MyProgram {
    public static void main(String[] args) {
		Cat mimi = new Cat("Mimi the fab",2);   //Using the constructor!
    }
}
class Cat {
  int age;
  String name;
  Cat(String a, int b) {  //Defining the constructor
    name = a;
    age = b;
  }
}

The constructor here is the special function Cat(String a, int b). Java knows this is the "constructor" for class Cat because the function is the same name as the class. If we named it anything other than "Cat", then Java wouldn't recognize this function as a constructor. In addition, constructors cannot have return types. They can't even have the return type void! This is another way to identify a constructor.

How to use the constructor

You can only a constructor when you are creating a variable with "new Cat(....)". The action "new Cat(...)" does two things in Java: it creates the object in the computer memory, and it also runs the constructor with the parameters in the parenthesis. So if we run new Cat("joe",5), then String a will be "joe" and int b will be 5.

In the above example, we are setting the fields equal to the parameters of the constructor: name = a; age = b. This is very common. Very often we make a constructor so that every time we create the object we can give it some important variables. We did not have to create a constructor that takes two arguments exactly. We could've made a constructor that just takes a name:

public class MyProgram {
    public static void main(String[] args) {
		Cat mimi = new Cat("Mimi the fab");   //Notice we don't pass a second int argument when running the constructor
		System.out.println(mimi.age); //prints 42!
    }
}
class Cat {
  int age;
  String name;
  Cat(String a) {  //Defining the constructor
    name = a;
    age = 42;      //all cats start with age = 42
  }
}

The default constructor

You may say -- hey... why didn't I have to write a constructor with the first class:

public class MyProgram {
    public static void main(String[] args) {
		Cat mimi = new Cat(); //this is a constructor call! new Cat() <-- calling
    }
}
class Cat {
  int age;
  String name;
}

If you do not write any constructors for a class, Java automatically writes on for you! In reality, the class above is identical to this class:

public class MyProgram {
    public static void main(String[] args) {
		Cat mimi = new Cat(); //this is a constructor call! new Cat() <-- calling
    }
}
class {
  int age;
  String name;
  Cat() {      //the "default" empty constructor, which is written for you automatically
    //advanced students should note that there is also an implicit call to super() here
  }
}

However, once you write at least one constructor, you overwrite this default constructor

Constructor overloading

You can also have multiple constructors in the same class:

public class MyProgram {
    public static void main(String[] args) {
		Cat mimi = new Cat("Mimi the fab");  //runs constructor 1
		System.out.println(mimi.age);     //prints 42
		Cat garfield = new Cat("Garfield",9001); //runs constructor 2
		System.out.println(garfield.age); //prints 9001

		//note we can not do new Cat() without parameters since both constructors above require parameters
    }
}
class Cat {
  int age;
  String name;
  Cat(String a) {  //Constructor 1
    name = a;
    age = 42;      
  }
  Cat(String a, int b) {  //Constructor 2
    name = a;
    age = b;
  }
}

Just like functions and methods, this is called overloading

The 'this' keyword

In certain circumstances, you may choose to name the arguments/parameters of a function the same name as the fields:

class Cat {
  int age;
  String name;
  Cat(String name, int age) { //two parameters with same name as fields
    this.name = name;
    this.age = age;
  }
}

In the above example, "this.age" refers to the FIELD age, while "age" refers to the parameter age. The reason that you need "this" is you can no longer refer to the field with just "age".



			
Run

Previous: Recursive Sort

Next: Oop Modifiers