Classes and Objects in Java – Fundamentals of OOPs

Free Java courses with 37 real-time projects - Learn Java

One of the main challenges that programmers face while writing code is that while writing lengthy codes, the code becomes haphazard and unorganized. It becomes very difficult to debug and look for errors while checking them line by line. Here comes the concept of OOPs programming which basically helps the programmer organize the program in a proper way. In this article, we will learn about classes and objects in java, polymorphism, inheritance, encapsulation and abstraction in java.

What are OOPs?

OOPs stands for Object-Oriented Programming. As we all know that Java is an Object Oriented Programming Language. OOPs programming language tries to map our code with real-world entities like objects, methods, inheritance, abstraction, etc, making the code short and easier to understand. OOPs also makes our programs easier to maintain and debug.

Advantages of Using OOPs:

  • Reusability of code(DRY[Don’t Repeat Yourself] principle.)
  • Data Hiding
  • Privacy and Security to our code
  • Low Maintenance cost
  • High Readability

Main Principles of OOPS:

OOPs mainly consists of 6 principles:

  • Class
  • Object
  • Abstraction
  • Inheritance
  • Polymorphism
  • Encapsulation

There are few other sub principles of OOPs that we will discuss at the end. They include:

  • Coupling
  • Cohesion
  • Association
  • Aggregation
  • Composition

Let Us Discuss Each and Every Principle One by One:

Classes in Java:

A class is a logical entity or blueprint from which objects can be created. A class can be described as a group of objects having common properties. Classes in java contain: Fields, Methods, Constructors, Blocks, Nested Classes and interfaces.

Syntax of a Class:

class <class name>{
//Statements
}

Objects in Java:

An object is a real-life entity of a class. A class is a logical entity whereas an object is a physical entity. A class is defined as a template or blueprint, it is only when an object is declared that memory is assigned to the program. An object has a proper state and behaviour. Objects are also known as instances of a class.

Syntax of an object:

<Class name> <Object name>= new <class name>();

Let us understand the relationship between classes and objects with a real-world example:

Suppose a student is filling an application form for an internship, he will fill the form and send it to the company. Here the application form is the class that contains fields like name, age, gender, etc which are the contents of the class. After the student fills the form, the final application of the student is known as the object.

Program to understand the above example:

package com.DataFlair.OOPS;
public class Internshipform
{
  String Name;
  int Age;
  String Gender;
  Internshipform(String name, int age,String gender) {
    this.Name = name;
    this.Age = age;
    this.Gender = gender;
  }
  public static void main(String args[]) {
    Internshipform obj1 = new Internshipform("Arka Ghosh", 21, "Male");
    Internshipform obj2 = new Internshipform("Aradhya Sarkar", 22, "Female");
    System.out.println("Name: " + obj1.Name);
    System.out.println("Age: " + obj1.Age);
    System.out.println("Gender: "+obj1.Gender);
    System.out.println("Name: " + obj2.Name);
    System.out.println("Age: " + obj2.Age);
    System.out.println("Gender: "+obj2.Gender);
  }
}

The output of the above Code:

Name: Arka Ghosh
Age: 21
Gender: Male
Name: Aradhya Sarkar
Age: 22
Gender: Female

Abstraction in Java:

Abstraction is the process of hiding implementation details from the end-user. In a programming language, we use a predefined object or previously created objects into another program without caring what that object contains, we only care about what it does. This type of implementation is known as abstraction.

Real-World Example of Abstraction:

We use mobile phones or smartphones to perform various tasks in our day to day life. Each application on the phone performs a specific task. We as users only care about what the application does, rather than focusing on how it does the task. This is known as abstraction.

In java, we can achieve abstraction through two processes:

  • Abstract Class[Partial Abstraction]
  • Interface[Complete Abstraction]

Let us take a look at them individually:

Java Abstract Class

A class with the keyword abstract in front of it is known as an abstract class. It can have both abstract and non-abstract methods. It cannot be initiated like other methods. The abstract methods need to be extended and implemented. We can achieve partial abstraction with abstract classes.

Program to illustrate Abstract Class:

package com.DataFlair.OOPS;
abstract class Internship
{
  abstract void success();  
}  
public class Status extends Internship{  
void success(){
    System.out.println("You Have Successfully Applied for the Internship!");
}  
public static void main(String[] args){  
 Internship obj = new Status();  
 obj.success();  
}  
}

The output of the above Program:

You Have Successfully Applied for the Internship!
Java Interface

As we know a class is a blueprint of a program, similarly, the blueprint of a class is known as an interface. Unlike abstract classes, interfaces cannot have normal methods, they only have abstract methods. Thus interfaces provide complete abstraction, unlike abstract classes.

Program to Illustrate Interface:

package com.DataFlair.OOPS;
interface Internship
{
    void print();
}
public class StatusofInternship implements Internship{  
public void print(){System.out.println("You Have Successfully Applied for the Internship!");
}  
public static void main(String args[]){  
StatusofInternship obj = new StatusofInternship();  
obj.print();  
 }  
}  

The output of the above Program:

You Have Successfully Applied for the Internship!

Inheritance in java:

Inheritance as the name suggests is the act of inheriting properties of the previously declared class. The class from which the properties are inherited is known as the parent class or superclass and the classes that derive from the main class is known as a subclass or child class. Inheritance uses the DRY principle. It is the act of deriving new things from previously existing things.

Real-World Example of Java Inheritance:

Phones were invented a long time ago, but that phone could only be used to communicate with others. In recent times, these phones have been replaced by smartphones, which inherited the properties of those phones and added new and improved features to them.

Types of Inheritance:

Program Illustrating Inheritance:

package com.DataFlair.OOPS;
public class Intern
{ 
 String name="Arka Ghosh";
}
public class Role extends Intern
{
    String Job="Technical Writer";
    String Lang="JAVA";
    void main(String[] args)
   {  
      Topic t=new Topic();  
      System.out.println("Intern Name: "+t.name);  
       System.out.println("Intern Role: "+t.Job+" in "+t.Lang);   
   }
}

The output of the above program:

Intern Name: Arka Ghosh
Intern Role: Technical Writer in JAVA

Encapsulation in java:

The wrapping up of data into a single entity; for example Class; is known as encapsulation. It is the act of putting various entities together. In java, encapsulation helps to keep the sensitive data hidden from the users.

Real World example of encapsulation:

Let us consider Laptop to be a single entity. A laptop contains a speaker, Keyboard, Mouse(Trackpad), wifi, etc. We can say that all these components are encapsulated into a single device known as a laptop.

Encapsulation can be done by making all the data members of a class private. The class is then provided with a setter and getter method to set and get the data. Java Bean class is an example of an encapsulated class.
Encapsulation provides control over data, data hiding, better unit testing, easy and fast creation.

Program to Illustrate encapsulation:

Encapsulated Class:
package com.DataFlair.OOPS;
public class Interns
{  
private String name;   
public String getName(){  
return name;  
} 
public void setName(String name){  
this.name=name;
}  
}
Access Class:
package com.DataFlair.OOPS;
public class AssignIntern
{
    public static void main(String[] args)
    {   
     Interns I=new Interns();  
     I.setName("Arka Ghosh");  
     System.out.println(I.getName());  
}  
}

The output of the above program:

Arka Ghosh

Polymorphism in java

Polymorphism means many forms. In java, polymorphism can be achieved using method overloading and method overriding. When a method has the same name but differs in either return type or parameter list they are known as overloaded functions and are an example of polymorphism.

There are two types of polymorphism in java; namely, compile-time polymorphism and runtime polymorphism.

RealWorld example of Polymorphism:

A smartphone can be used as a phone to make calls, it can also be used as a calculator. Hence, we can see that the entity is the same but the function differs, this is known as Polymorphism.

Program Illustrating Polymorphism:

package com.DataFlair.OOPS;
public class Polymorphism
{
    void area(int r)
    {
        double a=3.14*r*r;
        System.out.println("The area of the Circle is: "+a);
    }
    void area(int l, int b)
    {
        int a= l*b;
        System.out.println("The area of the rectangle is: "+a);
    }
    public static void main(String[] args)
    {
        Polymorphism a = new Polymorphism();
        a.area(5);
        a.area(2,3);
    }
}

The output of the above program:

The area of the Circle is: 78.5
The area of the rectangle is: 6

A few of the other important terms included in the OOPs Principle are discussed below:

Coupling

Coupling refers to the access to information that one class has on the other. If a class can access every information of another class, then the classes are known to be strongly coupled. In java, there are access modifiers to modify the access to the information a class gives by adding public, private or protected. For weaker coupling interfaces can be used as there is no proper implementation.

Cohesion

The level of an entity that performs a single well-defined task is known as cohesion. When an entity performs a single well-defined task on its own, the entity is said to be highly cohesive. The weakly cohesive entities will split the task. The java.io package is highly cohesive, as it has I/O related classes and interfaces only. The java.util package is an example of a weakly cohesive entity, as it has unrelated classes and interfaces.

Association:

Association is the relation between the objects and how they are mapped inside the program. Just like functions in mathematics, object mapping can also be done in four ways:

  • One to one
  • One to many
  • Many to one
  • Many to many

Association can be unidirectional as well as bi-directional.

Aggregation:

Aggregation represents the weak relationship between two objects. It can be termed as has-a relationship in java just like inheritance which represents the is-a relationship. Aggregation is basically another way to reuse objects. Aggregation is a way to achieve association.

Composition:

Composition represents a strong relationship between the containing object and the dependent object. It is a process where the containing object does not have an independent existence. If the dependent object is deleted the containing object will also be automatically deleted. It is also another way to achieve association.

Advantages of OOPs over Procedural Programming Language:

Programmers have shifted to OOPs programming, there must be a reason behind that. Let us see why OOPs programming has a clear advantage over Procedural Programming Language.

1. OOPs, provide an organized way to access and debug a program thus maintaining the program becomes easier. In procedural programming, each line has to be debugged separately to look for errors, which sometimes become too chaotic.

2. OOPs, provide security and protection to our data by hiding data using abstraction, encapsulation, etc. Procedural Programming doesn’t have such provisions.

3. OOPs, can be used to simulate real-life problems and thus can help solve those problems through different algorithms. With Procedural language, this is impossible to achieve.

Conclusion:

In this article, we saw why OOPs took over the programming world and helped us solve different issues. We discussed each and every terminology of OOPs with real-life examples to make it easier for everyone to understand the importance of OOPs.

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

follow dataflair on YouTube

4 Responses

  1. shravan says:

    i read the java documents ant it completed providing the java feature with example.

  2. devil says:

    question is not showing correctness of answer

Leave a Reply

Your email address will not be published. Required fields are marked *