Java – Classes and Objects

Java – Classes and Objects

Classes and ObjectsJava is an object oriented programming language. As a language that has an object-orientation function, it supports the following basic concepts:

  • polymorphism;
  • inheritance;
  • encapsulation;
  • abstraction;
  • classes;
  • objects;
  • copy;
  • method;
  • parsing.

In this tutorial, we will look at objects and classes in Java , their concepts.

java - objects & classes

A class can be defined as a template (marked in green) that describes the behavior of an object, which in turn has state and behavior. It is an instance of the class. For example: a dog can have a state – color, name, as well as behavior – nod, bark, eat.

Objects in Java

Let’s now take a deeper look at what objects are. If we look at the real world, we will find many objects around us, cars, dogs, people, etc. They all have a condition and lifestyle.

If we consider a dog, then its condition is name, breed, color, and its lifestyle is barking, tail wagging, running.

If you compare a program object in Java with objects from the real world, then they have very similar characteristics, they also have state and behavior. Programmatic state is stored in fields, and behavior is displayed through methods.

Thus, in software development, methods operate on the internal state of an object, and communication with others is carried out using methods.

Classes in Java

The class from which the individual objects are created is highlighted in green.

An example of creating a class in Java is given below:

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

   void barking(){
   }
   
   void hungry(){
   }
   
   void sleeping(){
   }
}

A class can contain any of the following kinds of variables:

  • Local variables defined inside methods, constructors, or blocks. They will be declared and initialized in the method, and will be destroyed when the method completes.
  • Instance variables are variables within a class, but also outside any method. They are initialized at boot. Instance variables can be accessed from within any method, constructor, or blocks of that particular class.
  • Class variables or static class variables in Java are declared in a class outside of any method using a static keyword.

In Java, classes can have any number of methods to access the value of various kinds of methods. In the above example, barking (), hungry () and sleeping () are methods.

The following are some of the important topics that must be covered in order to understand the meaning of classes and objects in a programming language.

Class constructor

When discussing class, one of the most important subtopics in Java is the constructor. Each class has a constructor. If we don’t write it, or forget, for example, the compiler will create it by default for this class.

Every time a new object is created in Java, at least one constructor will be called. The main rule is that they must have the same name as a class, which can have more than one constructor.

An example constructor is shown below:

public class Puppy {
    public Puppy () {
    }

    public Puppy (String name) {
       // This is what a constructor looks like in Java and has one parameter, name.
    }
}

Note: In the next sections, we will discuss in more detail if we have two different types of constructors.

Object creation

The options for how to create an object in a class are as follows:

  • Declaration : Declaring a variable with the name of a variable with an object type.
  • Instantiation : a “new” keyword is used.
  • Initialization : The “new” keyword is followed by a constructor call. This call initializes a new object.

An example is shown below:

public class Puppy {

    public Puppy (String name) {
       // This is a constructor and has one parameter, name.
       System.out.println ("Name to pass:" + name);
    }
    public static void main (String [] args) {
       // Create myPuppy object.
       Puppy myPuppy = new Puppy ("Baguette");
    }
}

If you compile and run the above program, it will produce the following output:

Name passed: Baguette

Accessing instance variables and methods in Java

Variables and methods are available through the created objects. To access an instance variable, the full path should look like this:

/ * Create object first * /
ObjectReference = new Constructor ();

/ * Now call the variable like this * /
ObjectReference.variableName;

/ * Now you can call the class method * /
ObjectReference.MethodName ();

Example

This example explains how to access instance variables and class methods in Java:

public class Puppy {
   
   int puppyAge;

   public Puppy (String name) {
      // This is a constructor and has one parameter, name.
      System.out.println ("Passed name:" + name);
   }
   public void setAge (int age) {
       puppyAge = age;
   }

   public int getAge () {
       System.out.println ("Puppy age:" + puppyAge);
       return puppyAge;
   }
   public static void main (String [] args) {
      / * Create an object. * /
      Puppy myPuppy = new Puppy ("Baguette");

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

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

      / * Get a class instance variable. * /
      System.out.println ("Variable value:" + myPuppy.puppyAge);
   }
}

If you compile and run the above program, it will produce the following output:

Name passed: Baguette
Puppy age: 2
Variable value: 2

Rules for declaring classes, imports, and packages in a source file

In the last part of this section, let’s look at the rules for declaring a source file. These rules in Java are important when declaring classes, import statements, and package statements in a source file.

  • There can be only one public class in the source file.
  • A source file can have several “non-public” classes.
  • The name of the public class must be the same as the name of the source file, which must have a .java extension at the end. For example: the class name is public class Employee {} , then the source file should be Employee.java .
  • If the class is defined within a package, then the package statement must be the first statement in the source file.
  • If import statements are present, they must be written between the package statements and the class declaration. If there are no package statements, then the import statement must be the first line in the source file.
  • The import and package statements will execute in the same way for all classes present in the source file. In Java, it is not possible to declare different import and / or package statements to different classes in a source file.

Classes have several levels of access and there are different types of classes: abstract classes, final classes, etc. We will discuss all this in the lesson access modifiers .

Apart from the above class types, Java also has some special classes called Inner classes and Anonymous classes.

Java package

When developing applications, hundreds of classes and interfaces will be written, so categorizing these classes is a must, and it also makes life a lot easier.

Import statements

By specifying a fully qualified name that includes the package and the class name, the compiler can easily find the source code or classes. In Java, imports are a way of giving the compiler the right place to find a particular class.

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

import java.io.*;

A simple example as described above

For our training, we will create two classes. These will be the Employee and EmployeeTest classes.

First, open notepad and add the following code. Remember that this Employee class is a public or public class. Now save the original file named Employee.java.

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

import java.io. *;
public class Employee {
   String name;
   int age;
   String designation;
   double salary;

   // This is the constructor for the Employee class.
   public Employee (String name) {
      this.name = name;
   }
   // Assign the employee's age to the age variable.
   public void empAge (int empAge) {
      age = empAge;
   }
   / * Assign to the variable designation. * /
   public void empDesignation (String empDesig) {
      designation = empDesig;
   }
   / * Assigning to the salary variable. * /
   public void empSalary (double empSalary) {
      salary = empSalary;
   }
   / * Display detailed information. * /
   public void printEmployee () {
      System.out.println ("Name:" + name);
      System.out.println ("Age:" + age);
      System.out.println ("Name:" + designation);
      System.out.println ("Salary:" + salary);
   }
}

As mentioned above, processing starts from the main method. So for us to run the Employee class, there must be a main method and objects created. Let’s create a separate class for these tasks.

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

Save the following code to the EmployeeTest.java file:

import java.io. *;
public class EmployeeTest {

    public static void main (String args []) {
       / * Create two objects using the constructor. * /
       Employee empOne = new Employee ("Oleg Olegov");
       Employee empTwo = new Employee ("Ivan Ivanov");

       // Call the method for each created object.
       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, with both classes compiled, run EmployeeTest and get the following result:

C:> javac Employee.java
C:> vi EmployeeTest.java
C:> javac EmployeeTest.java
C:> java EmployeeTest
Name: Oleg Olegov
Age: 26
Name: Senior Software Engineer
Salary: 1000.0
Name: Ivan Ivanov
Age: 21
Name: Software Engineer
Salary: 500.0