logo

Java Object And Classes


Show

Java is known to be an Object-Oriented Language. As a programming language that has the Object-Oriented characteristic, Java sustains the following basic concepts:

  • Classes
  • Objects
  • Instance
  • Method
  • Polymorphism
  • Abstraction
  • Inheritance
  • Encapsulation
  • Message Passing

In this Java tutorial, we will look into the concepts - Classes and Objects.

  • Object − Objects have conditions and performances. Example: A dog has conditions - color, name, breed as well as actions – wagging the end, barking, consumption. An object is an example of a class.
  • Class − A class can be described as a guide /proposal that explains the behavior/state that the thing of its type holds up.

Objects in Java

Let us now seem profound into what are objects. If we believe the real world, we can find numerous objects approximately us, cars, dogs, persons, etc. All these objects have a condition and actions.

If we believe a dog, then its condition is - name, breed, shade, and the deeds are - barking, wagging the end, running.

If you evaluate the software entity with a real-world article, they have awfully parallel characteristics.

Software objects too have a condition and a performance. A software object's state is amassed in fields and activities is exposed via methods.

Therefore, in software development, processes operate on the interior state of an entity and the object-to-object statement is done via systems.

Classes in Java

A class is a plan from which entity objects are generated.

Following is a sample of a class.

Example

public class Dog {
   String breed;
   int age;
   String color;

   void barking() {
   }

   void hungry() {
   }

   void sleeping() {
   }
}

A class can contain any of the following variable types.

  • Local variables − Variables characterized surrounded by methods, constructors or blocks are entitled limited variables. The variable will be asserted and initialized inside the technique and the changeable will be obliterated when the technique has been completed.
  • Instance variables − Instance variables are uneven in a class except exterior any process. These changeable are initialized while the class is instantiated. Example variables can be contacted from within any process, constructor or lumps of that exacting class.
  • Class variables − Class patchy are variables stated in a class, exterior any method, with the stationary keyword.

A class can encompass any number of processes to admission the value of a variety of kinds of techniques. In the above example, barking(), hungry() and sleeping() are methods.

Following are several of the imperative topics that require to be argued when searching into classes of the Java programming language.

Constructors

When conferring concerning to the classes; one of the mainly significant sub-subject would be constructors. Each class has a constructor. If we do not clearly write a constructor for a class, the Java compiler constructs a defaulting constructor for that division.

Every time a new item is generated, at slightest one constructor will be raised. The key rule of constructors is that they must encompass the identical name as the set. A class can contain more than one constructor.

Following is an example of a constructor −

Example

public class Puppy {
   public Puppy() {
   }

   public Puppy(String name) {
      // This constructor has one parameter, name.
   }
}

Java too holds Singleton Classes where you would be capable to generate only one case of a class.

Note − we have two dissimilar kinds of constructors. We are leaving to argue constructors in feature in the following chapters.

Creating an Object

As mentioned beforehand, a class supplies the plans for objects. So an object is produced from a class. In Java, the novel keyword is employed to produce new objects.

There are three paces when creating an entity from a class −

  • Declaration − A variable statement with a changeable name with an item type.
  • Instantiation − The 'new' keyword is utilized to generate the object.
  • Initialization − The 'new' keyword is pursued by a entitle to a constructor. This identify initializes the new object

Following is an example of creating an object:

Example

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

   public static void main(String []args) {
      // Following statement would create an object myPuppy
      Puppy myPuppy = new Puppy( "tommy" );
   }
}

If we compile and run the above program, then it will produce the following result:

Output

Passed Name is :tommy

Accessing Instance Variables and Methods

Instance variables and methods are accessed via created objects. To access an instance variable, the following is the fully qualified path −

/* First create an object */
ObjectReference = new Constructor();

/* Now call a variable as follows */
ObjectReference.variableName;

/* Now you can call a class method as follows */
ObjectReference.MethodName();

Example

This example explains how to access instance variables and methods of a class.

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) {
      /* Object creation */
      Puppy myPuppy = new Puppy( "tommy" );

      /* Call class method to set puppy's age */
      myPuppy.setAge( 2 );

      /* Call another class method to get puppy's age */
      myPuppy.getAge( );

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

If we compile and run the above program, then it will produce the following result:

Output

Name chosen is :Tommy
Puppy's age is :2
Variable Value :2

Source File Declaration Rules

As the previous fraction of this part, let's now seem into the source file statement rules. These rules are necessary when declaring classes, introduce statements and enclose statements in a source file.

  • Their container is only one public division per source file.
  • A source file can have several non-public classes.
  • The public class forename should be the given name of the source file too which should be added by .java at the end. For instance: the class name is public class Employee{} then the source folder should be as Employee.java.
  • If the class is identified surrounded by a package, then the package account should be the primary statement in the source file.
  • If introduce statements are near, then they must be written between the wrap-up statement and the class declaration. If there are no pack-up statements, then the import statement should be the primary line in the source file.
  • Import and wrap-up statements will entail all the classes here in the source file. It is not potential to announce diverse import and/or package statements to diverse classes in the source file.

Classes have numerous access heights and there are dissimilar types of classes; conceptual classes, last classes, etc. We will be explained concerning all these in the admission modifiers chapter.

Apart from the above-mentioned kinds of classes, Java also has several special classes called inside classes and unidentified classes.

Java Package

In easy words, it is a method of categorizing the groups and lines. When rising applications in Java, hundreds of classes and lines will be written, consequently categorizing these classes is a necessity as well as builds life much easier.

Import Statements

In Java, if a completely qualified name, which includes the package and the class name, is given, then the compiler can effortlessly place the source code or classes. Import statement is a method of giving a good location for the compiler to discover that exacting class.

For case, the subsequent line would inquire the compiler to load entire the classes accessible in directory java_installation/java/io −

import java.io.*;

A Simple Case Study

For our container study, we will be creating two classes. They are Employee and EmployeeTest.

First, open the notepad and add the following code. Remember this is the Employee class and the class is a public class. Now, save this source file with the name Employee.java.

The Employee class has four instance variables - name, age, designation, and salary. The class has one explicitly defined constructor, which takes a parameter.

Example

import java.io.*;
public class Employee {

   String name;
   int age;
   String designation;
   double salary;

   // This is the constructor of the class Employee
   public Employee(String name) {
      this.name = name;
   }

   // Assign the age of the Employee  to the variable age.
   public void empAge(int empAge) {
      age = empAge;
   }

   /* Assign the designation to the variable designation.*/
   public void empDesignation(String empDesig) {
      designation = empDesig;
   }

   /* Assign the salary to the variable	salary.*/
   public void empSalary(double empSalary) {
      salary = empSalary;
   }

   /* Print the Employee details */
   public void printEmployee() {
      System.out.println("Name:"+ name );
      System.out.println("Age:" + age );
      System.out.println("Designation:" + designation );
      System.out.println("Salary:" + salary);
   }
}

As stated before in this tutorial, dispensation starts from the major method. Consequently, in order for us to run the Employee class, there should be a chief method and objects should be produced. We will be creating a disconnected class for these tasks.

Following is the EmployeeTest class, which creates two instances of the class Employee and invokes the methods for each object to assign values for each variable.

Save the following code in the EmployeeTest.java file.

import java.io.*;
public class EmployeeTest {

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

      // Invoking methods for each object created
      empOne.empAge(26);
      empOne.empDesignation("Senior Software Engineer");
      empOne.empSalary(1000);
      empOne.printEmployee();

      empTwo.empAge(21);
      empTwo.empDesignation("Software Engineer");
      empTwo.empSalary(500);
      empTwo.printEmployee();
   }
}

Now, compile both the classes and then run EmployeeTest to see the result as follows:

Output

C:\> javac Employee.java
C:\> javac EmployeeTest.java
C:\> java EmployeeTest
Name:James Smith
Age:26
Designation:Senior Software Engineer
Salary:1000.0
Name:Mary Anne
Age:21
Designation:Software Engineer
Salary:500.0