Easy Tutorial
❮ Number Ceil File Create ❯

Java Objects and Classes

Java, as an object-oriented language, supports the following fundamental concepts:

This section focuses on the concepts of objects and classes.

In the diagram below, boy and girl are classes, while each individual person is an object of that class.

In another diagram, car is a class, and each specific car is an object of the car class, which includes details like color, brand, and name.


Objects in Java

Let's delve deeper into what an object is. Observing the real world around us, we find many objects like cars, dogs, and people. All these objects have their own states and behaviors.

Taking a dog as an example, its states include name, breed, and color, while its behaviors include barking, wagging its tail, and running.

Comparing real-world objects to software objects, they are quite similar.

Software objects also have states and behaviors. The state of a software object is represented by attributes, and behaviors are manifested through methods.

In software development, methods manipulate the internal state of objects, and the interaction between objects is also achieved through methods.

Classes in Java

A class can be seen as a template for creating Java objects.

Below is a simple class definition to understand classes in Java:

public class Dog {
    String breed;
    int size;
    String colour;
    int age;

    void eat() {
    }

    void run() {
    }

    void sleep(){
    }

    void name(){
    }
}

A class can contain the following types of variables:

A class can have multiple methods, as seen in the example above: eat(), run(), sleep(), and name() are all methods of the Dog class.


Constructors

Every class has a constructor. If you do not explicitly define a constructor for a class, the Java compiler provides a default constructor.

When creating an object, at least one constructor must be called. The constructor's name must match the class name, and a class can have multiple constructors.

Here is an example of a constructor:

public class Puppy{
    public Puppy(){
    }

    public Puppy(String name){
        // This constructor has only one parameter: name
    }
}

Creating an Object

Objects are created based on classes. In Java, a new object is created using the keyword new. Creating an object involves three steps:

Here is an example of creating an object:

public class Puppy{
   public Puppy(String name){
      // This constructor has only one parameter: name
      System.out.println("Puppy's name is : " + name ); 
   }
   public static void main(String[] args){
      // The following statement will create a Puppy object
      Puppy myPuppy = new Puppy( "tommy" );
   }
}

Compiling and running the above program will produce the following result:

Puppy's name is : tommy

Accessing Instance Variables and Methods

Instance variables and methods are accessed through an instantiated object, as shown below:

/* Instantiate an object */
Object referenceVariable = new Constructor();
/* Access variables in the class */
referenceVariable.variableName;
/* Access methods in the class */
referenceVariable.methodName();

Example

The following example demonstrates how to access instance variables and call member methods:

public class Puppy{
   int puppyAge;

   public Puppy(String name){
      // This constructor has one parameter: name
      System.out.println("Name chosen is : " + name ); 
   }

   public void setAge( int age ){
       puppyAge = age;
   }

   public int getAge( ){
       System.out.println("Puppy's age is : " + puppyAge ); 
       return puppyAge;
   }

   public static void main(String[] args){
      /* Create an object */
      Puppy myPuppy = new Puppy( "tommy" );

      /* Set age */
      myPuppy.setAge( 2 );

      /* Get age */
      myPuppy.getAge( );

      /* You can also access instance variables as follows */
      System.out.println("Variable Value : " + myPuppy.puppyAge ); 
   }
}

Compiling and running the above program will produce the following result:

Name chosen is : tommy
Puppy's age is : 2
Variable Value : 2
public Puppy(String name) {
    // This constructor has one parameter: name
    System.out.println("Puppy's name is: " + name);
}

public void setAge(int age) {
    puppyAge = age;
}

public int getAge() {
    System.out.println("Puppy's age is: " + puppyAge);
    return puppyAge;
}

public static void main(String[] args) {
    /* Create an object */
    Puppy myPuppy = new Puppy("tommy");
    /* Set age via method */
    myPuppy.setAge(2);
    /* Call another method to get age */
    myPuppy.getAge();
    /* You can also access member variables like this */
    System.out.println("Variable value: " + myPuppy.puppyAge);
}

Compiling and running the above program will produce the following result:

Puppy's name is: tommy
Puppy's age is: 2
Variable value: 2

Source File Declaration Rules

At the end of this section, we will learn about the source file declaration rules. These rules are essential when declaring multiple classes in a single source file, along with import and package statements.

Classes have various access levels and can also be categorized as abstract, final, etc. These will be covered in the access control section.

In addition to the types mentioned above, Java also has special classes like inner classes and anonymous classes.


Java Packages

Packages are primarily used to categorize classes and interfaces. When developing Java programs, hundreds or thousands of classes and interfaces might be written, so categorizing these is necessary.

Import Statements

In Java, if a fully qualified name, including the package and class name, is given, then the Java compiler can easily locate the source code or classes. Import statements are used to provide a path to make it easier for the compiler to find a particular class.

For example, the following command line will instruct the compiler to load all the classes available in java_installation/java/io:

import java.io.*;

A Simple Example

In this example, we create two classes: Employee and EmployeeTest.

First, open a text editor and paste the following code. Save the file as Employee.java.

The Employee class has four member variables: name, age, designation, and salary. This class explicitly declares a constructor that takes one parameter.

Employee.java File Code:

import java.io.*;

public class Employee {
   String name;
   int age;
   String designation;
   double salary;
   // Constructor of the class Employee
   public Employee(String name) {
      this.name = name;
   }
   // Set the age value
   public void empAge(int empAge) {
      age = empAge;
   }
   /* Set the designation value */
   public void empDesignation(String empDesig) {
      designation = empDesig;
   }
   /* Set the salary value */
public void empSalary(double empSalary){
   salary = empSalary;
}
/* Print information */
public void printEmployee(){
   System.out.println("Name: " + name);
   System.out.println("Age: " + age);
   System.out.println("Designation: " + designation);
   System.out.println("Salary: " + salary);
}

The program starts execution from the main method. To run this program, a main method must be included and an instance object must be created.

Below is the EmployeeTest class, which instantiates two instances of the Employee class and calls methods to set the values of variables.

Save the following code in the EmployeeTest.java file.

EmployeeTest.java File Code:

import java.io.*;
public class EmployeeTest{

   public static void main(String[] args){
      /* Create two objects using constructor */
      Employee empOne = new Employee("tutorialpro1");
      Employee empTwo = new Employee("tutorialpro2");

      // Invoke methods for each object
      empOne.empAge(26);
      empOne.empDesignation("Senior Programmer");
      empOne.empSalary(1000);
      empOne.printEmployee();

      empTwo.empAge(21);
      empTwo.empDesignation("Junior Programmer");
      empTwo.empSalary(500);
      empTwo.printEmployee();
   }
}

Compile these files and run the EmployeeTest class to see the following results:

$ javac EmployeeTest.java
$ java EmployeeTest 
Name: tutorialpro1
Age: 26
Designation: Senior Programmer
Salary: 1000.0
Name: tutorialpro2
Age: 21
Designation: Junior Programmer
Salary: 500.0
❮ Number Ceil File Create ❯