Java Class & Java Objects: Learn Java Class & Java Objects in full details

Java Class & Java Objects:

Java Class & Java Objects

Java Class & Java Objects: The fundamental components of OOP’s are Classes and objects. Often there is confusion among classes and objects. We try to tell you the difference between class and object in this tutorial.

Java is an Object-Oriented Programming Language. As a programming language that has the Object-Oriented feature, Java supports the following fundamental concepts like −

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

In this session, we will look into the concepts of – Classes and Objects.

  • Object − Objects have behaviors and states. Example: A car has states – color, engine type, wheels, etc as well as behaviors – this can run at 180kmph, it can turn right and left, it can go back and forth, it can carry 4 people, etc. A java object is an instance of a class.
  • Class − A Java class can be defined as a template/blueprint that describes the behavior/state that the object of its type support.

Difference Between Java Class & Java Objects?

A class is a blueprint that defines the variables and the methods common to all objects of a certain kind.

An object is a specimen of a java class. Software objects are often used to model real-world objects we find in everyday life.

What is Java Object:

java object

Let us now look deep into what are the objects are. If you consider the real-world entity, then you can find many objects around you like cars, dogs, humans, etc. All of these objects have a state and some behavior.

If we consider a car, then its state is – color, engine type, wheels, etc and the behavior is – a car can run at 180kmph, it can turn right and left, it can go back and forth, it can carry 4 people, etc.

If we compare the software object with the real-world object or entity, they also have very similar characteristics.

Also, have a state and behavior of Software objects. A software object’s behavior is shown via methods and state is stored in fields. Methods operate on the internal state of an object and the object-to-object communication is done via methods in software development.

What is java class:

Java class | what is java class

Class is a blueprint or a set of instructions to build a specific type of object.

Example:

public class Car{
   String color;
   String engineType;
   String brandName;

   void SetSpeed() {
   }

   void StartEngine() {
   }
}

Java Class & Java Objects: A class can contain the following variable types:

  • Local variables − Local variables are defined inside methods, constructors or blocks. The variable will be destroyed when the method has completed and the variable will be declared and initialized within the method.
  • Instance variables − the instance variables are variables within a class but outside any method. Instance variables are initialized when the class is instantiated. From inside any method, constructor or blocks of that particular class, instance variables can be accessed.
  • Class variables − Class variables are those variables declared within a class, outside any method, with the static keyword.

A java class can have any number of methods to access the value of various kinds of methods. In the above example, SetSpeed() and StartEngine()  are methods.

The following are some of the important topics that we need to be discussed when looking into classes of the Java Language.

Java Constructors:

One of the most important sub-topics would be constructors when discussing java classes. In java, every class has a constructor. If you do not explicitly define a constructor for a class then Java compiler builds a default constructor for that class.

At least one constructor will be invoked when a new object is created. It’s the main rule for java that they should have the same name as the class. In java, a class can have more than one constructor.

Learn java constructors’ full details.

Example

public class Car{
   public Car() {
   }

   public Car(String brandName) {
      // This constructor has one parameter only, brandName.
   }
}

Actually, Java also supports Singleton Classes where we would be able to create only one instance of a class.

Note − There two types of constructors.

Learn java constructors’ full details.

Java Object Create:

A class provides the blueprints for objects as we mentioned previously. So actually an object is created from a class. The new keyword is used to create a new object in java programming.

We are following three steps when creating an object from a class-

  • Declaration − Declaration of a variable with a variable name and an object type.
  • Instantiation − using the “new” keyword we create an object.
  • Initialization − The ‘new’ keyword is followed by a call to a constructor. This call initializes the new object.

Example:

public class Car{
   public Car(String brandName) {
      // This constructor has accept one parameter, name.
      System.out.println("The brand Name is :" + name );
   }

   public static void main(String []args) {
      // The following statement would create an object myCar
      Car myCar = new Car( "Toyota" );
   }
}

It will produce the following result −

Output:

The brand Name is :Toyota

Accessing Instance Variables and Methods

To create an object we can access instance variables and methods. To access any instance variable, to the following is the fully qualified path –

/* First we have to create an object */
ObjReference = new Constructor();

/* Now we have to call a variable as follows */
ObjReference.variableName;

/* Now we can call a class method as the follows */
ObjReference.MethodName();

Example:

Here, we explain how to access instance member variables and member methods of a class.

public class Car{
   int CarAge;

   public Car(String brandName) {
      // This constructor method has one parameter only, brandName.
      System.out.println("Car brand Name is :" + brandName );
   }

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

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

   public static void main(String []args) {
      /* Here we create Object */
      Car myCar = new Car( "Toyota" );

     /* To Call class method to set Car's age using this code */
      myCar.setAge( 4 );

      /* Call another class method to get the Car's age */
      myCar.getAge( );

      /* We can access instance variable follwing this code */
      System.out.println("The variable Value :" + myCar.CarAge );
   }
}

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

Output

Car brand Name is :Toyota
Car's age is :4
The variable Value :4

Source File Declaration Rules in java:

Let’s now look into the source file declaration rules as the last part of this section. When declaring classes these rules are essential, import statements and package statements in a source file.

  • Per source file, there can be only one public class.
  • Multiple non-public classes are only for a source.
  • Actually the public class name should be the name of the source file as well which should be appended by .java at the end. For example, the class name is public class SoftwareEngineer{} then the source file should be as SoftwareEngineer.java.
  • If we find the class is defined inside a package, then the package statement should be the first statement in the source file.
  • They must be written between the package statement and the class declaration if import statements are present. The import statement should be the first line in the source file if there are no package statements.
  • Import and package statements will imply to all the classes present in the source file. Actually it is not possible to declare different import or package statements to the different classes in the source file.

Types of classes in Java:

There are different types of classes and Classes have several access levels like abstract classes, final classes, etc. In the access modifiers chapter, we will be explaining about all these.

Java also has some special classes called Inner classes and Anonymous classes, apart from the above-mentioned types of classes.

Java Package:

It is a way of categorizing the classes and interfaces, in simple words. The hundreds of classes and interfaces will be written, therefore we can categorizing these classes is a must as well as makes life much easier when we developing applications in Java.

Java Import Statements:

In Java, if a fully qualified name, which includes the package and the class name is given, then the compiler can easily locate the source code or classes. Import statement is a way of giving the proper location for the compiler to find that particular class.

For example, the following line would ask the compiler to load all the classes available in directory java_installation/java/io −

import java.io.*;

A Simple Case Study:

We will be creating two classes for our case study. They are Engineers and SoftwareEngineer.

First, open your notepad and add the following code blew. One thing that you have to remember this is the Engineers class and this class is a public class. Now, save this source file with the name Engineers.java.

The Engineers class has four instance variables – fullName, age, designation, and salary. The class has one explicitly defined constructor, which accepts a parameter.

Example

import java.io.*;
public class Engineers{

   String fullName;
   int age;
   String designation;
   double salary;

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

   // Assign the age of the Engineers to the variable age.
   public void setAge(int engAge) {
      age = engAge;
   }

   /* Assign the designation to the variable of designation.*/
   public void setDesignation(String engDesig) {
      designation = engDesig;
   }

   /* To assign the salary to the variable salary.*/
   public void engSalary(double engSalary) {
      salary = engSalary;
   }

   /*Now Print the Engineers details */
   public void EngineersDetails() {
      System.out.println("Name:"+ fullName);
      System.out.println("Age:" + age );
      System.out.println("Designation:" + designation );
      System.out.println("Salary:" + salary);
   }
}

In this chapter as we mentioned previously, processing starts from the main method. Therefore, in order for us to run this Engineers class, actually, there should be a main method and objects should be created. Actually will be creating a separate class for these particular 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.

Now Save the following code in SoftwareEngineer.java file.

import java.io.*;
public class SoftwareEngineer{

   public static void main(String args[]) {
      /* Create two objects using constructor method */
      Engineers engOne = new Engineers("Jo J. Phillips");
      Engineers engTwo = new Engineers("Pamela H. Stanfield");

      // Invoking methods for each object creation
      empOne.setAge(21);
      engOne.setDesignation("Senior Software Engineer");
      engOne.engSalary(35000);
      engOne.EngineersDetails();

      engTwo.setAge(31);
      engTwo.setDesignation("Software Engineer");
      engTwo.engSalary(30000);
      engTwo.EngineersDetails();
   }
}

Now, compile both the classes and then run SoftwareEngineer to see the result as follows −

Output

C:\> javac Engineers.java
C:\> javac SoftwareEngineer.java
C:\> java SoftwareEngineer
Name:Jo J. Phillips
Age:21
Designation:Senior Software Engineer
Salary:35000.0
Name:Pamela H. Stanfield
Age:31
Designation:Software Engineer
Salary:30000.0
Close