Java Classes and Objects

As we already know Java is an object-oriented programming language. The object-oriented programming concepts start from a class and object. These are the basic and fundamental concepts of object-oriented programming techniques. In this lesson, we are going to learn about what is a class and what is an object and how we can use these.

What are classes and objects?

We can think of a class as a plan or blueprint which defines the content and behaviour of an object. In real world, using a single blueprint, you can build multiple buildings. Each of these buildings is an object.

So how Java uses classes and objects? In Java, class defines the specifications to construct an object. Objects are instances of classes. A class contains data and has pre defined operations to perform on the data. This data is called data members of the class and the operations are called methods of the class. Together these are called members of the class.

A class definition starts with the class keyword followed by name of the class. The complete class is included within curly brackets. All data members and methods are written inside this block. Below is the simple syntax of a class:

class classname {

  type var1;
  type var2;
  ...
  type varN;

  type method1(parameters) {
  }
  type method2(parameters) {
  }
  ...
  type methodN(parameters) {
  }
}

Till now we have seen single class in the main method. As you already know the main method is the entry point for our program. Next, we will learn how to create our own classes which can be called from the main method.

Taxi class:

To demonstrate how to create classes let’s take an example of taxi class which represents real world objects like car, vans and buses. This class is called the taxi and it will store some information about it: Maximum number of passengers that it can carry, fuel capacity, and type of fuel. The below example shows the number of passengers is represented by integer variable passengers, fuel capacity is represented by capacity and type of fuel represented by type

class taxi {

    int passengers;
    int capacity;
    byte type;    
}

Creating object:

The class definition is a blueprint without any physical presence in the memory. No memory will be created for this class definition. But to use this class we need to create objects. As this object is physically present, memory will be created for this object. This object is called an instance of the class. A class can have multiple instances, each instance having a unique variable name.

To create an object of taxi class we need to use new keyword. This new keyword creates memory for our object and assigns a handle to the memory to the minivan object variable.

taxi minivan = new taxi();

Accessing data members

Data members can only be accessed thru objects. To access a data member of an object, we can use the dot (.) operator, the syntax is given below:

object.data_member

Now let’s assign values to data members of our mini van object as below,

minivan.passengers = 6;
minivan.capacity   = 45;
minivan.type       = 0;  //Desel

Now create another object SUV of class taxi and initialize data members.

taxi suv = new taxi();
suv.passengers = 5;
suv.capacity   = 55;
suv.type       = 1;//Petrol

Let’s execute below program and we will print all data members of two objects. From the output, it is clear that our two objects are completely two different instances which mean that they have their own properties. These properties are also called instance members or instance variables of the class.

/*
This is a simple Java program about Class. Call this file KH_ClassDemo.java.
*/

class taxi {
    int passengers;
    int capacity;
    byte type;    
}

public class KH_ClassDemo {
	// A Java program begins with a call to main().
	public static void main(String args[]) {
		taxi minivan = new taxi();
		minivan.passengers = 6;
		minivan.capacity = 45;
		minivan.type = 0;//Desel.
		
		taxi suv = new taxi();
		suv.passengers = 5;
		suv.capacity = 55;
		suv.type = 1;//Petrol
		
		System.out.println("Minivan Passengers capacity: " + minivan.passengers);
		System.out.println("Minivan Fuel capacity: " + minivan.capacity);
		System.out.println("Minivan type of fuel: " + minivan.type);
		System.out.println("");
		System.out.println("suv Passengers capacity: " + suv.passengers);
		System.out.println("suv Fuel capacity: " + suv.capacity);
		System.out.println("suv type of fuel: " + suv.type);
	}
}

Download the code Run the code

Output:

Minivan Passengers capacity: 6
Minivan Fuel capacity: 45
Minivan type of fuel: 0

suv Passengers capacity: 5
suv Fuel capacity: 55
suv type of fuel: 1

Constructors

In the above example, we initialised all our data members in separate statements. This kind of initialization is not used professionally as it is error prone. Java provides a better approach to initialize data members of a class while creating an object. This mechanism is called a constructor.

A constructor is simply the name of a class with open and close parenthesis and a code block to it. Inside this constructor, we can give default values to our data members. For example for taxi class, we can create a default constructor.

public taxi() {
    passengers = 4;
    capacity = 30;
    type = 0;//Desel
}

In some cases, you may want to specify initial values to your data members while creating object. This can be achieved by using a parameterized constructor. A parameterized constructor takes one or more parameters as input and we can write code to assign these parameters to data members. These parameters can be defined within parentheses by specifying data type and name of the parameter. More than one parameter can be separated by using a comma.

public taxi (int p, int c, byte t) {
    passengers = p;
    capacity = c;
    type = t;
}

Lets us modify our taxi class and add two constructors. One default constructor and other with parameters. The output of this below program will explain everything about how to use these constructors.

/*
This is a simple Java program about Class.
Call this file KH_ClassDemo1.java.
*/

class taxi {

    int passengers;
    int capacity;
    byte type;
	
	public taxi () {
		passengers = 4;
		capacity   = 30;
		type       = 0;  //0=Diesel 1=Petrol
	}
	
	public taxi (int p, int c, byte t) {
		passengers = p;
		capacity = c;
		type = t;
	}    
}

public class KH_ClassDemo1 {
	// A Java program begins with a call to main().
	public static void main(String args[]) {
		taxi minivan = new taxi ();
		taxi suv = new taxi (5, 55, (byte)1);
		
		System.out.println ("Minivan Passengers capacity: " + minivan.passengers);
		System.out.println ("Minivan Fuel capacity: " + minivan.capacity);
		System.out.println ("Minivan type of fuel: " + minivan.type);
		System.out.println ("");
		System.out.println ("suv Passengers capacity: " + suv.passengers);
		System.out.println ("suv Fuel capacity: " + suv.capacity);
		System.out.println ("suv type of fuel: " + suv.type);
	}
}

Download the code Run the code

Output:

Minivan Passengers capacity: 4
Minivan Fuel capacity: 30
Minivan type of fuel: 0

suv Passengers capacity: 5
suv Fuel capacity: 55
suv type of fuel: 1
<<< Java arraysJava garbage collection and access modifiers >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .