Classes and Objects in Java – Fundamentals of OOPs
Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java
One of the main challenges that programmers face while writing code is that, while writing lengthy code, 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 properly organize the program. However, 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, 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 in Java:
- Reusability of code(DRY[Don’t Repeat Yourself] principle): OOPs concepts like inheritance simplify the work in a way that previously written code can be used again by other classes & in other programs.
- Data Hiding: Abstraction is useful in terms of hiding the data. It showcases only the required information.
- Privacy and Security of our code: It is achieved using access modifiers to maintain the integrity of the data.
- Low Maintenance cost: The oops principle has the benefit of easy debugging of the code, and reusing the code, which results in overall low maintenance of the application.
- High Readability: Hierarchical presentation of the code by using inheritance makes it more readable. Also, packing up the data using encapsulation increases the readability of a program.
Main Principles of OOPs in Java
OOPs mainly consists of 6 principles:
- Class
- Object
- Abstraction
- Inheritance
- Polymorphism
- Encapsulation
There are a few other sub-principles of OOP that we will discuss at the end. They include:
- Coupling
- Cohesion
- Association
- Aggregation
- Composition
Let Us Discuss Each Principle One by One:
Classes in Java
A Java 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 in Java:
class <class name>{
//Statements
}
Objects in Java
An object in Java 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 a Java 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 out an application form for an internship, he will fill out 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 objects and classes in Java:
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:
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 in 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 Java Abstraction
We use mobile phones or smartphones to perform various tasks in our day-to-day lives. 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 Java class with the keyword abstract in front of it is known as an abstract class. Th, it can have both abstract and non-abstract methods. It cannot be initiated like other methods. The abstract methods in Java need to be extended and implemented. We can achieve partial abstraction with abstract classes.
Program to illustrate Abstract Class in Java:
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:
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 in Java:
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:
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 are known as subclasses or child classes. Although Inheritance uses the DRY principle. Therefore, 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 they 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 in Java
Program of Java 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 Role: Technical Writer in JAVA
Encapsulation in Java
The wrapping up of data into a single entity, for example, a class, is known as encapsulation. However, it is the act of putting various entities together. Therefore, in Java, encapsulation helps to keep the sensitive data hidden from the users.
Real-world example of encapsulation in Java
Let us consider the laptop to be a single entity. A laptop contains a speaker, Keyboard, Mouse(Trackpad), wifi, etc. Although 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. Thus, the class is then provided with a setter and getter method to set and get the data. Therefore, A Java Bean class is an example of an encapsulated class. As a result, Encapsulation provides control over data, data hiding, better unit testing, and easy and fast creation.
Program to Illustrate Encapsulation in Java:
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:
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 an overloaded function and is an example of polymorphism.
Although there are two types of polymorphism in Java, namely, compile-time polymorphism and runtime polymorphism.
Real-world example of Java Polymorphism
A smartphone can be used as a phone to make calls, and 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 in Java
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 rectangle is: 6
A few of the other important terms included in the OOPs Principle are discussed below:
Java Coupling
Coupling in Java refers to the access to information that one class has on the other. If a class can access all the information of another class, then the classes are known to be strongly coupled. However, 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 in Java
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. Hence, 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 in Java
Association is the relation between the objects and how they are mapped inside the program. Similar to, 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 bidirectional.
Java Aggregation
Aggregation represents the weak relationship between two objects. It can be termed as a has-a relationship in Java, just like inheritance, which represents the is-a relationship. Therefore, Aggregation is basically another way to reuse objects. Therefore, aggregation is a way to achieve association.
Composition in Java
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 languages.
1. OOPs provide an organized way to access and debug a program, thus making maintaining the program easier. However, in procedural programming, each line has to be debugged separately to look for errors, which sometimes becomes too chaotic.
2. It provides security and protection to our data by hiding data using abstraction, encapsulation, etc. Therefore, 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. However, we discussed each and every terminology of OOPs with real-life examples to make it easier for everyone to understand the importance of OOPs.
Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google


i read the java documents ant it completed providing the java feature with example.
Thanks Shravan for liking DataFlair’s Java tutorials. Hope you are able to learn java with it.
question is not showing correctness of answer
15 is answer