Objects and Classes in Java

ObjectsClassesEncapsulation

In the previous blog, we learned about Array, its declaration, initialization, accessing the array elements, etc. If you want to know more about Arrays, visit Arrays in Java. In this blog, we will go through the concept of Objects and Classes in Java. This blog will give you a deep understanding of the OOP, objects, classes, how to create objects, etc.

Introduction to OOP(Object Oriented Programming)

OOP stands for Object Oriented Programming Language. It has replaced the structured programming techniques developed in the 1970s. An OOP(Object Oriented Program) is made up of objects. Each object depicts some functionalities, hidden implementations, etc. Many objects in the program can be taken from the library and some can be custom designed.


Methodology Used in POP(Procedural Oriented Programming) VS OOP(Object Oriented Programming)

In a procedural language like C, a set of procedures were defined to solve the problem, and once the procedure was defined, the next step was to find a suitable way to store the data. So here algorithms were in the first place and then data structure. This reflected the way programmers used to work in that period. But OOP works in reverse order, first, it puts the data and then looks at the algorithm that will be used to operate on the data.


Classes

A class is a template or design(blueprint) from which the objects are made. When you construct an object, then it creates an instance of the class. In Java, all the code is written inside the class. Class is the collection of methods and variables. We define a class using the keyword "class". The general syntax of the class is as follows:

Syntax:

class  {
  member variables;
  methods;
}

e.g.

public class StudEx {
  int rollNo;
  String name;
  public void displayResult();
}

In the above example we have written public at the beginning of the class, it is nothing but the access specifier. We will learn about Access Specifiers in the later blog. public access specifier will allow the class to be accessible to all other classes. There will be no restriction in accessing this class. Next to the public keyword, we can see the class keyword, it is nothing but the keyword for defining the class followed by its name. Then we have declared variables and methods. Here even for methods, we have used public, the same concept is applied here like class, it will be accessible by all the other classes.


Encapsulation

Encapsulation is the process of wrapping up the variables(data) and methods by hiding internal details from the user. For this reason, it is also called information hiding. The variables will be hidden from the other classes. They will be only accessible through the methods of that class. The real-time example is watch. The watch only shows us the time, it hides the internal working of the watch from the user. We can create a class that is fully encapsulated by making its data members private. The variables that store the data in bits are called instance fields and the functions that operate on that data are called methods. The object which is an instance of the class will have values of its instance fields(instance variables).

e.g.

class EncapsulationEx {
  private long intValue;
  private String strName;
  public long getIntValue() {
      return intValue;
  }
  public void setIntValue(long intValue) {
      this.intValue = intValue;
  }
  public String getStrName() {
      return strName;
  }
  public void setStrName(String strName) {
      this.strName = strName;
  }
}

Output:

//Class to test the encapsulated class EncapsulationEx
public class TestEncapsulation {
    public static void main(String[] args) {
        EncapsulationEx ex = new EncapsulationEx();
        ex.setIntValue(12315089999L);
        ex.setStrName("Java Shortkicks");
        System.out.println(ex.getIntValue() + " " + ex.getStrName());
    }
}

Objects in Java

Objects are basically an entity which has some state, behavior. e.g. glass, cup, computer, book, etc. The object has three characteristics.

  1. State - The state represents the value of the data. It also describes how the object will react when we invoke the method.
  2. Behavior - It represents the behavior of the object. It also depicts what methods can be applied on this object.
  3. Identity - Describes how the object is different from the other object that has the same state and behavior. e.g. Car is an object, named Ford, having color as black which is the state and used for driving is the behavior. The state of an object may mutate. If the state of an object changes, it is due to the method calling it. But if its state changes without method calls, then it means that encapsulation is broken. The state of an object doesn’t fully describe the object, it is because each and every object has a distinct(different) identity.

e.g.

public class ObjectEx {

  public String name;

  public String color;

  public String brand;

  public String getName(){
      return name;
  }
  public void setName(String name){
      this.name = name;
  }
  public String getColor(){
      return color;
  }
  public void setColor(String color){
      this.color = color;
  }
  public String getBrand(){
      return brand;
  }
  public void setBrand(String brand){
      this.brand = brand;
  }
  public static void main(String[] args) {
      ObjectEx objEx = new ObjectEx();
      objEx.setName("Car");
      objEx.setColor("black");
      objEx.setBrand("Ford");
      System.out.println("Name:" + objEx.getName() + " " + "Color:" + objEx.getColor() + " " + "Brand:" + objEx.getBrand());
  }
}

Output:

Name:Car
Color:black
Brand:Ford

Identifying Classes in Java

As we are already aware that in C we write programs with the main function. We cannot proceed further without the main function. main() is the entry point for all the programs in C. But in Object Oriented Programming(OOP) there is no top, so beginners get confused from where to start. The simple answer to this question is to identify the class and then add the methods to the class. The very simple rule for identifying the classes is that the class always starts or begins with nouns like Car, Student, Account, Person, etc, and methods always start with verbs like display, add, withdraw, etc. Suppose we take the example of Account then Account is the noun which is class and withdraw, display, etc are its methods which are verbs.


Relationship between Classes in Java

There are following relationship between classes

  1. Dependence(Uses-A)
  2. Aggregation(Has-A)
  3. Inheritance(Is-A)

Dependence(Uses-A)

Dependence relationship is also known as uses-a relationship. Dependence relationship is a relationship where we create an object of a class inside the method of another class. It is the most frequently used relationship.

e.g.

class Atrowel{
  -----------
}

class JavaShortkicks {
  //Another Class use as as a parameter
  Public Void getBlogsList(Atrowel objAtrowel, String type) {
      ----------
  }

  //Another Class use as a return
  Public Atrowel displayAtrowelResult() {
      Atrowel atrowelObj = new Atrowel();
      ----------
      Return atrowelObj;
  }
}

In the application if several classes depend on each other, then the coupling(elements are strongly connected to other elements) between the classes is high. In order to reduce the coupling we must minimize the dependency between the classes. If the dependency is reduced between the class, then the coupling between classes becomes low. In the application, if there are some modifications in the class and because of which its behavior changes, then this will affect all the classes that are dependent on that class. So in order to overcome this we must reduce the coupling of the classes, so that we can easily maintain those classes.


Aggregation(Has-A)

Aggregation is also called has - a relationship. Aggregation is when an object of the class is created as a data member of another class and has-a relationship. e.g. Student has an address. Has - a relationship shows a whole-part relationship. Now in the Student Address example, the Student represents the whole and the Address represents the part. There is no feature in Java that will denote the has - a relationship.

e.g.

classs Atrowel {
  -----------
}

class JavaShortkicks{
  Public Atrowel atrowelObj;
}

e.g.

class Address{
  ---------
}

class Student{
  Address object = new Address;
}

Other example is “a car has a engine”. Now here the car is whole and the engine is a part. We cannot say that the engine has a car which is not correct.

e.g.

class Engine {
  ---------
}

class Car {
  Engine engine = new Engine();
}

Inheritance(Is-A)

Inheritance is also known as is - a relationship. When a superclass(base class) establishes a relationship with the subclass (child class) is called inheritance or is - a relationship. In other words, the child class which is the subclass or derived class inherits all the properties of the super class or parent class. e.g. We will take the example of humans. All humans hold some properties of their ancestors. e.g. Child holds some properties of his father which are the properties of his father, in short, the boy indirectly inherits the properties of his grandfather. Inheritance(Is-a) relationship is denoted by keyword extends.

e.g.

class Atrowel {
  ---------
}

class JavaShortkicks extends Atrowel {
  ---------
}

e.g.

class Father {

}

class Child extends Father {

}

Core Java Tutorial

Get in Touch

Atrowel will be pleased to receive your feedback and suggestions. Those of you who would like to contribute, please send us an email.