JAVA CLASSES AND OBJECTS

Java Class and Objects are one of the main features of Java Object Oriented Programming. In this module we will design programs using classes and Objects.

Table of Contents

[hide]
  • Class in Java
  • Class Declaration in Java
  • Object in Java
  • Using Objects in Java

Class in Java

The Class in Java is the basic unit of object-orientation. The Class is often described as a user-defined model that creates an object. It allows a programmer to define all the properties and methods that internally define an object. A Class in Java contains :

  • 1. fields
  • 2. functions/methods
  • 3. blocks
  • 4. constructors etc

Variables that are declared within a class are known as instance variables and these are used by methods to perform certain operations. Instance variables along with method are also known as class members.

Class do not occupy any space in the memory. To declare a class, class keyword is used.

Important Points to Remember : -

  • Top level class in java cannot be defined as a private class, only public and default access specifiers are allowed. We will learn more about Java Modifiers in upcoming tutorials.

  • Only one public class in allowed in a single Java program. Name of the class should be same as that of the a Java file.

Class Declaration Important Components

A class in general can include the following components : -

Modifiers

Modifiers are the keywords that we use in the definition of a class,method or variable. A class can be public or can have default access.

Class name

In Java,the class name usually represents nouns that should start with a capital letter without space.

Superclass (if any)

The parent class name is a superclass,and the child class is a subclass. The child class inherits the parent's properties using the extends keyword. Only a single parent will inherit a subclass.

Interfaces (if any)

To define an interface,we simply write the keyword interface followed by the name of the interface. A class can implement more than one interface

Class Body

The class body surrounded by braces,{}.

Java Class Syntax

class class_name {
field;
constructor;
method;
}

Example 1: Java Class Bike Declaration

copyimage
//Java Program to illustrate a simple Java class representing a Bike
class Bike {
       // fields
       String name;
       String model;
       int speed;

       // constructor
       Bike (String name, String model) {
       this.name = name;
       this.model = model;
       }

      // methods
      int BikeSpeed(int accelerate) {
      this.speed = this.speed + accelerate;
      return this.speed;
     }
   //continue..
}

The above example is just a simple example of the declaration of a class, kindly don't copy the example and try to run in your java environment.

A Java Class here represents a Bike, which holds fields to hold the state, and its behavior is decribed by methods, while constructor used to create objects from this class. Don't worry if you did not get the concepts clear now, we have a separate tutorial about each of the following.

Object in Java

We have already learned about the basics of object in the last tutorial Java OOP's Concepts. In this module we will go in detail about what is an object, how do we create it etc.

An object in Java is an instance of a class and consists of properties and its behaviors. Objects are created using the new operator along with the class constructor. We will now create an object of Bike type.

javaobject

The Statement above follows three Simple steps for declaring any Object :-

  • 1. Declaration
  • 2. Instantiation
  • 3. Initialization

Declaration of an Object Variable

Declaration of object variable is same as that of variable, we just use object is place of data type. If you still dont know how to declare a variable kindly refer Java Variable module.

Java Objects resides insides heap memory area and contains some address. Lets see how we declare an object variable.

object reference

Here we have not yet declared an object. We have just declare a reference variable that is empty until assigned. To create an object we need to instantiate with the new operator.

Instantiation of an Object

A new operator will instantiate a class by assigning memory to a new object in the heap memory. A new operator requires a call to the constructor. The name of the constructor provides the name of the class to instantiate. The new object is initialised by the constructor.

object instantiate

Now we will take the above example of Bike object and initialize it with the constructor values. Lets take the bike example of above where we have passed the arguments to the constructor i.e name, model.

Initialization of an Object

We pass constructor's argument to initialize an object. Constructor takes three arguments in this example i.e name, model and speed. These arguments are then provided with values like name of the bike is hayabusa, model is BS6 and speed is 300.

object instantiate

Constructor name is same as that of a class and has no return type. We will learn about constructor and method in detail in the upcoming module. From this module you just have to understand the basics i.e how class is defined and how you can create an object.

Now since we know how to declare, instantiate and initialize an object. Now we will learn how do we use the created object.

Using Objects in Java

Once we've created an object, we may need details from it, we may want to change its status, or we may want some action to be taken. There are three ways to do these things : -

  • 1. By Reference variable
  • 2. By calling method
  • 3. By calling constructor

Java Class and Object Example : By Reference Object Variable

In Java we can access the data memebers or object fields by their name. The .dot operator is used to refer to object members as :-

objectreference.membername

Example 1: Accessing member fields with bike Object as a reference.

copyimage
//Java Program to access object fields by their name
public class Bike {
      // fields
      String name;
      String model;
      int speed;

    
         public static void main(String args[]){  
         Bike bike = new Bike(); // creating object

         // initializing an object
         bike.name = "Suzuki Hayabusa";
         bike.model = "BS6";
         bike.speed = 300;

         
         // Printing data values using dot operator with member name
         System.out.println("bike name is =" + " " + bike.name);
         System.out.println("bike model is =" + " " + bike.model);
         System.out.println("bike speed is =" + " " + bike.speed);
    }
}

OUTPUT :

bike name is = Suzuki Hayabusabike model is = BS6bike speed is = 300

Example 2: Same example with main outside the class

While working in large scale project it is better to create multiple classes and use them from other classes. Keep in mind that name of the class containing main method should be same as that of file name.

copyimage
//Java Program to access object fields by their name
 class BikeDemo {
      // fields
      String name;
      String model;
      int speed;
}
    public class Bike {
         public static void main(String args[]){  
         BikeDemo bike = new BikeDemo(); // creating object

         // initializing an object
         bike.name = "Suzuki Hayabusa";
         bike.model = "BS6";
         bike.speed = 300;

         
         // Printing data values using dot operator with member name
         System.out.println("bike name is =" + " " + bike.name);
         System.out.println("bike model is =" + " " + bike.model);
         System.out.println("bike speed is =" + " " + bike.speed);
    }
}

Output is same as that of above, while copying and pasting the above program in your text editor kindly make sure that your file name is same as that of the class containing main method. In our case file name is Bike.java.

Example 3: Garbage Collector

We use a reference variable to access the object member fields from heap memory. If we try to create another object of the same class with the same reference variable, the old object would be destroyed and automatically will be handled by the garbage collector, and the newly created object will point to the same reference variable.

copyimage
//Java Program to access object fields by their name
 class BikeDemo {
      // fields
      String name;
      String model;
      int speed;
}
    public class Bike {
         public static void main(String args[]){  
         BikeDemo bike = new BikeDemo(); // creating object

         // initializing an object
         bike.name = "Suzuki Hayabusa";
         bike.model = "BS6";
         bike.speed = 300;

         // object pointed to the new reference
         bike = new BikeDemo();

         // Printing data values using dot operator with member name
         System.out.println("bike name is =" + " " + bike.name);
         System.out.println("bike model is =" + " " + bike.model);
         System.out.println("bike speed is =" + " " + bike.speed);
    }
}

OUTPUT :

bike name is = nullbike model is = nullbike speed is = 0
object instantiate

Java Class and Object Example : By calling Method

You may use a reference object to invoke a method, it is invoked by appending the name of the method to the object reference with dot operator.

Objectreference.methodname(arguments if any);

In the next tutorials, we will learn more about the methods in detail.

Example 1: Accessing Method with bike Object as a reference.

copyimage
//Java Program to display bike features and speed via methods
class BikeExample {
     // fields
     String name;
     String model;
     int speed;

     // method 
     void bikefeatures(String n, String m, int s) {
     name=n;
     model=m;
     speed=s;
     }

     // method
     void displayInfo() {
     System.out.println("bike name is =" + " " + name);
     System.out.println("bike model is =" + " " + model);
     System.out.println("bike name is =" + " " + speed);
   }
}

  public class Bike {
      public static void main(String args[]){  
         BikeExample bike = new BikeExample(); // creating object
         bike.bikefeatures("suzuki hayabusa","BS6",300);
         bike.displayInfo();
    }
}

The output of the program is same as that of previous program

Java Class and Object Example : By calling Constructor

Constructor have the same as that of a class. It is called when the instance of a class is created, when constructor is called allocation of memory to object is done. It is a type of method that is used to initialize object.

copyimage
//Java Program to display bike features and speed via methods
class BikeExample {
    // fields
    String name;
    String model;
    int speed;

    // Constructor - same name as that of class 
    BikeExample(String n, String m, int s) {
    name=n;
    model=m;
    speed=s;
    }

    // method
    void displayInfo() {
    System.out.println("bike name is =" + " " + name);
    System.out.println("bike model is =" + " " + model);
    System.out.println("bike name is =" + " " + speed);
  }
}

  public class Bike {
     public static void main(String args[]){  
       BikeExample bike = new BikeExample("suzuki hayabusa","BS6",300); // passing values
       bike.displayInfo();
    }
}

In the upcoming tutorials, we will learn more about the Constructor in detail.