Object Oriented Programming In Java

Introduction

 
In this article, we will learn about Object-Oriented Programming in Java with its different concepts like Class, Object, Inheritance, Abstraction, Encapsulation, and Polymorphism with example programs.
 

Java 

 
Java technology is both a programming language and a platform. It is a high-level, class-based, and object-oriented programming language. Java is a secure and powerful language. Java runs on multiple platforms. It means that it can work on any software or hardware platform. It has a virtual machine specification. It has its own runtime environment JRE (Java Runtime Environment) and an API (Application Programming Interface) Specification. The Java programming language is a high-level language.
 
The following type of applications are developed in Java,
  • Standalone Application
  • Web Application
  • Enterprise Application
  • Mobile Application
To learn more about how to program in Java, Click Java Basics.
 

Object-Oriented Programming

 
Java is an object-oriented programming language. It means that all things are objects in Java and in other words, we can say that Java is a collection of objects.
  • Object
  • Class
  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation
Object Oriented Programming
 

Advantages of Object-Oriented

 
The following are the advantages of the Oops in Java:
  • It makes the development procedure easy.
  • Oops provides an efficient way to interact with real-world data.
  • Real-world problems can be solved easily by the Oops concept.
  • Data hiding is the main advantage of the Oops concept.
  • Data can be shared anywhere in the project through the Oops concepts.

Class in Java

 
Java class is the basic building block of the Java programming language. Java class is a template that is used to create objects, and to define data types and methods. Java class objects should have basic class properties.
 
Java class is the basic concept of object-oriented programming languages. Java class is a user-defined template or blueprint where objects, data members, and methods are defined with a set of instructions to build a specific type of object. The variables and methods of the same Java class are common for all the objects of the class. In Java, the class keyword is used to define a Java class. 
 

How is a Java Class defined?

 
Syntax
 
class <class-name>
{
    [data members];
    [methods];
}
 
The code example of the Java class is listed below.
  1. public class ClassExample {  
  2.   
  3.     //Data Members  
  4.     int x = 5;  
  5.     int y = 10;  
  6.   
  7.     void method() {  
  8.         System.out.println("This is method");  
  9.     }  
  10.   
  11.     public static void main(String args[]) {  
  12.   
  13.         ClassExample obj = new ClassExample();  
  14.   
  15.         int c = obj.x + obj.y;  
  16.         System.out.println(c);  
  17.   
  18.         obj.method();  
  19.     }  
Explanation of the program
 
class ClassExample{
the class keyword is used to declare a class in Java such as ClassExample is a class name. 
 
Data Members
int x = 5;

int y = 10;
 
We create two integer-type variables named x and y.
 
void method()
We create a method of the void type named method().
 
Public static void main(String args[]){
Public is an access modifier and is publically accessible everywhere which means it’s visible to all.
 
static
Static is a keyword. When we use a static keyword with any method, it is called a static method. It is used basically in memory management and there is no need to create an object to call it a static method.
 
void
Void is a return type and it’s not returning any value to a method.
 
main
Main is used to start a program. Without main, you cannot run your program.
 
String [] args
String [] args is used for a command-line argument.
 
int c= obj.x + obj.y;
In this line we create a variable c and store the addition of x and y in that variable and print the c in the next line "System.out.println(c);
 
obj. method()
Here we call the method of the class by the object of the class.
 
The above program generates the following output.
 
Class Output Image1
 

Objects in Java

 
An object is a basic concept of oops like java classes. objects like an entity, which has a state and behavior like car, mobile, pencil, cat, etc. A car has states (its color, name, and brand) and behavior (running). Objects are an instance of a java class and objects can be tangible and intangible. Objects represent identity, which uniquely identifies it. Like one car's number plate is a different number from other cars. So, it is the car's identity that is unique.
 
Objects represent the value of an object like car name, color, and brand. Objects represent the functionality of an object like a car's functionality is running.
 

How to create an object in the Java class?

 
In Java a new keyword is used to create an object.
 
Syntax
 
<class-name> [object-name] = new <class-default-conetructor>
 
The complete example program of Object is listed below.
  1. public class ObjectExample {  
  2.     public static void main(String args[]) {  
  3.   
  4.         ObjectExample obj = new ObjectExample();  
  5.   
  6.         System.out.println(obj.getClass());  
  7.     }  
Explanation
 
In the above code example first, we create a new Java class named "ObjectExample".
 
ObjectExample obj= new ObjectExample();
This line is used to create the object of the class.
 
obj.getClass()
obj is the object name of the class and getclass() method is used to get the name of the class.
 
The above code generates the following output. 
ObjectClass Output
 

Inheritance in Java

 
In Java, Inheritance is a process, where one class object acquires all the properties and behaviors of the parent class object. It represents the IS-A relationship, also called a parent-child relationship. With the use of an inheritance, we can manage the information easily.
 
In an inheritance, we can create new classes, which are built upon the existing classes. The main benefit of inheritance is we can reuse the methods and variables of the parent class, add new methods and variables also. The class, which acquires the properties of the parent class is called a subclass (derived class, child class) and the class, whose properties are acquired are called a superclass (base class, parent class).
 

Parent class in Java Inheritance 

 
The class that is inherited by the other classes is called the Parent class, Superclass, and base class also.
 

Child class in Java Inheritance

 
The class which inherits the parent class is called the child class, subclass, and derived class also.
 

Advantages of Inheritance in Java

  • Code reusability
    Code Reusability is the main advantage of the inheritance in Java because we can extend the classes, so the code of the parent class can be used in the child classes which inherit that parent class. 
     
  • Method overriding
    In the Method Overriding concept of inheritance in Java, the parent class and child class has the method with the same name and same return type. 
Syntax of Inheritance
 
class Subclass-name extends Superclass-name
{
          //variables and methods;
}
 
 
Note
In Java, the “extends” keyword is used to inherit the properties of a class.
 
The complete program example of inheritance in Java is listed below.
  1. public class Vehicle {  
  2.     int carSpeed = 90;  
  3.   
Explanation
 
First, we create a parent class named Vehicle, In this class, we create an integer type variable named "carSpeed=90".
  1. public class Car extends Vehicle {  
  2.     int speed= 60;  
  3.   
  4.     public static void main(String args[]){  
  5.         Car c = new Car();  
  6.         System.out.println("Vehicle Speed : " +c.speed);  
  7.         System.out.println("Vehicle Speed : " +c.carSpeed);  
  8.     }  
Explanation
 
Here we create a child class named Car and extend the Vehicle class, we create an integer type variable named  speed=60. We create the object of the car class. Now we use the object of the car class to access the variables of the parent class and the child class.
 
The above program generates the following output.
 
Inheritance Example
 

Types of Inheritance in Java

 
In Java, there are various types of inheritance which are shown below

1. Single inheritance in Java

 
Single Inheritance Image
 

2. Multilevel Inheritance in Java

 
Multilevel Inheritance Image
 

3. Hierarchical Inheritance in Java

 
Hierarical Inheritance Image
 

4. Multiple Inheritance in Java 

 
Multiple Inheritance Image
 

5. Hybrid Inheritance in Java

 
Hybrid Inheritance Image
 
On the basis of class, three types of inheritance in Java exist, which are single, multilevel, and hierarchical.

In Java, multiple and hybrid inheritance are not supported through the class. Both are supported through the interface only.
 

Why is Multiple inheritance not supported in Java?


Java is a very powerful and simple language. Multiple inheritance increases the complexity of a program. To reduce the difficulty and make language simple, Java does not support multiple inheritance.

Suppose, we have three classes X, Y, and Z. Z is a child class and inherits the properties of class X and class Y. X and Y both are parent classes. If X and Y classes have the same method and when we want to call that method from child class object, it gives an error since there will be an ambiguity (confusion) to call method X or Y class. Due to this, Java does not support multiple inheritance through classes.
 
 

Polymorphism in Java 

 
Polymorphism means many forms. Polymorphism is the capability of an object to take on many forms. In Polymorphism, we can do a single task by different ways.
 
Java mainly uses polymorphism in OOPS, which occurs when a parent class reference is used to refer a child class object.
 
In Java, there are two types of polymorphism, which are-
  • Compile-time polymorphism
  • Runtime polymorphism
We can do polymorphism by method overloading and method overriding.
 

Compile-time polymorphism in Java

 
When we overload the static method in Java, it is called a compile-time polymorphism. In other words, we can say, if a class has more than one method with the same name but different arguments.
  
The complete program example of compile-time polymorphism in Java is listed below.
  1. public class PolymorphismExample1 {  
  2.     void add(int x, int y) {  
  3.         System.out.println(x + y);  
  4.     }  
  5.   
  6.     void add(int x, int y, int z) {  
  7.         System.out.println(x + y + z);  
  8.     }  
  9.   
  10.     public static void main(String args[]) {  
  11.         PolymorphismExample1 obj = new PolymorphismExample1();  
  12.         obj.add(102030);  
  13.         obj.add(3020);  
  14.     }  
  15.   
Explanation
 
In the example, shown above, we create add () method and overload that method with the different argument. It is an example of compile-time polymorphism.
 
The above program generates the following output.
 
Polymorphism Example1
 

Run time Polymorphism in Java

 
In Java, runtime polymorphism is a process in which we call an overridden method, which is resolved at the runtime. It is also called a dynamic method dispatch.
 
In runtime polymorphism, an overridden method is called through the reference variable of a parent class.
 
The complete program example of Run time Polymorphism in Java is listed below.
  1. class RunTimePolymorphismexam1 {  
  2.   
  3.     void work() {  
  4.         System.out.println("working");  
  5.     }  
  1. public class RunTimePolymorphismexam2 extends RunTimePolymorphismexam1 {  
  2.     void work() {  
  3.         System.out.println("working hard");  
  4.     }  
  5.   
  6.     public static void main(String args[]) {  
  7.         RunTimePolymorphismexam1 e = new RunTimePolymorphismexam2();//upcasting  
  8.         e.work();  
  9.     }  
Explanation
 
In the example, shown above, first, we create two classes, RunTimePolymorphismexam1, and RunTimePolymorphismexam2. Programmer class inherits RunTimePolymorphismexam1 class and overrides the work () method of the parent class. We call the work method by the reference variable of the parent class and it refers to the child class object. Hence, the child class method is invoked at the runtime by JVM.
 
The above program example generates the following output.
 
Run Time Polymorphism example
 

Abstraction in Java 

 
In Java, abstraction is a procedure to hide the implementation details from the user and provides only functionality to the user.
 
In other words, it hides all the internal details and provides only important things to the user. For example in the calculator, when we want to calculate some data, we use its keys but we don’t know, how it works internally. It provides only important things to the user and hides the internal process from the user.
 
In Java, there are two ways to achieve abstraction, which are-
  • Abstract class
  • Interface

Abstract class in Java

 
In Java, when we use abstract keywords with any class, this class is called an abstract class.
  • An abstract class can have abstract methods and non-abstract methods.
  • If a class has an abstract method, this class must be an abstract class.
  • If we want to use an abstract class, it needs to be extended and its method implemented.
  • If we extend an abstract class, we have to provide an implementation for all the abstract methods in it.
  • We can’t instantiate an abstract class.
The complete example program of the Abstract class is listed below.
  1. abstract class Person {  
  2.     abstract void work();  
  1. public class Girl extends Person {  
  2.   
  3.     @Override  
  4.     void work() {  
  5.         System.out.println("Working Hard");  
  6.     }  
  7.   
  8.     public static void main(String args[]) {  
  9.         Person obj = new Girl();  
  10.   
  11.         obj.work();  
  12.     }  
Explanation
 
In this example, we create a person class, which contains one abstract method work and its implementation is provided by the women class.
 
The above program generates the following output.
 
Abstract class example
 

Abstract method in Java

 
In Java, when we use an abstract keyword with any method, the method is called an abstract method and an abstract method contains a method signature, but no method body.
 
The complete program example of an abstract method is listed below.
  1. abstract class AbstractMethod1 {  
  2.     abstract void call();  
  1. class AbstractMethod2 extends AbstractMethod1 {  
  2.   
  3.     //implementation is provided by others i.e. unknown by end user  
  4.     void call() {  
  5.         System.out.println("Abstract Method implementation");  
  6.     }  
  7.  
  1. class AbstractMethod3 extends AbstractMethod2 {  
  2.   
  3.     void call() {  
  4.         System.out.println("Abstract Method");  
  5.     }  
  6.   
  1. public class AbstratUserClass {  
  2.       
  3.     // method is called by programmer or user  
  4.       
  5.     public static void main(String args[]) {  
  6.           
  7.         AbstractMethod1 m = new AbstractMethod3();//object is provided through method  
  8.         m.call();  
  9.           
  10.     }  
Explanation
 
In this example, AbstractMethod1 class is an abstract class and its implementation is provided by AbstractMethod2 and AbstractMethod3 classes. In it, if we create an instance of AbstractMethod2 class, call () method of AbstractMethod2 class will be invoked similar to AbstractMethod3 class. In reality, we don’t know about the implementation class i.e. hidden to the user, and the object of the implementation class is provided by the factory method. 
 
An abstract class can have variables, an abstract method, a method body, a constructor, and a main () method also.
 
The above program generates the following output.
 
Abstract Method Example
 

Encapsulation in Java

 
In Java, encapsulation is a concept of OOPS. It is a procedure of wrapping the code and data together into a single unit, for example, tea is a mixture of several items.
 
Encapsulation is a process to bind related methods and variables in a protective wrapper (Class) with necessary access modifiers. With the use of encapsulation, the code can be secured from unauthorized access by others and is easy to maintain.
 
We can create a fully encapsulated class by creating all the data members of the class as private. Java provides setter and getter methods to set and get the data in it. An example of the fully encapsulated class is a Java bean class.
 

Advantages of Encapsulation

  • It provides control over the data. We can write the logic inside the setter method.
  • We can make our class read-only or write-only with the use of the setter and getter method.
  • It makes the code more secure, flexible, and maintainable.
  • In encapsulation, we can change one part of the code easily without affecting the other part of the code.
The complete program example of Encapsulation is listed below.
  1. package EncapsulationExample;  
  2.   
  3. public class EncapsulationExample1 {  
  4.     private String name;  
  5.   
  6.     public String getName() {  
  7.         return name;  
  8.     }  
  9.   
  10.     public void setName(String name) {  
  11.         this.name = name;  
  12.     }  
  1. package EncapsulationExample;  
  2.   
  3. public class EncapSulationExampleUSer {  
  4.   
  5.     public static void main(String[] args) {  
  6.   
  7.         EncapsulationExample1 b = new EncapsulationExample1();  
  8.   
  9.         b.setName("C#Corner");  
  10.         System.out.println(b.getName());  
  11.   
  12.     }  
  13.   
Explanation
 
In the example of the encapsulation program, First, we create a package named EncapsulationExample. In this package, we create two Java classes EncapsulationExample1 and EncapsulationExampleUser. The example program shown above has only one data member with its setter and getter methods.
 
The above program generates the following output.
 
Encapsulation Example Output
 

Summary

 
In this article, we will learn about Object-Oriented programming concepts in Java. We learn about Object, class, Inheritance, Polymorphism, Encapsulation, and Abstraction with example programs.