Quick Enquiry Form

×

    EnquiryEnquire Now

    Quick Enquiry

      Object Oriented Programming – Java OOPs Concepts With Examples

      Java OOPs Concepts with Examples
      Blog

      Object Oriented Programming – Java OOPs Concepts With Examples

      Object Oriented Programming

      Object-oriented programming (OOP) is a paradigm that makes available a wide range of programming ideas, including but not limited to inheritance, abstraction, polymorphism, etc. These ideas seek to incorporate real-world items into code by developing reusable methods and variables that don’t compromise safety. Java, C++, C#JavaScript, Python, Ruby, Perl, Smalltalk, etc. are just some of the most popular and influential object-oriented programming languages. Learn Java course in Chennai to master the OOPs concept in Java.

      Basics of OOPS

      First, let’s go over the basics by reviewing how to declare methods and pass messages. It has a total of six parts, beginning with the method declaration, which is as follows :

      • The access modifier: specifies how the method can be accessed inside the context of your application. The four distinct varieties of Java access specifiers are as follows:
      • Public: Available in all of your application’s classes.
      • Protected: it can only be accessed within the same package that it was defined in, as well as any subclasses that it may have (including subclasses declared outside the package).
      • Private: Only visible to other instances of the same class as its definition.
      • Default (declared/defined without a modifier): Applicable within the same class and package as its class definition.
      • The return type: It is the data type of the value that the method returns, or void if no value is returned.
      • Method Name: Method names follow the same standards as field names, with a few minor differences in style.
      • Parameter list: Input parameters are listed in a comma-separated list, with their data types specified in parenthesis. Parentheses must be used even if there are no parameters ().
      • Exception list: The expected exceptions thrown by the procedure. It is possible to make these alterations (s).
      • Method Body: The code between the braces is what has to be run in order to carry out the desired actions.

      Message Passing : Objects exchange information by sending and receiving messages. When an object receives a message, it interprets it as a command to carry out a certain procedure; the object then calls the appropriate function to produce the requested output. To send a message, you must first identify the object, the function, and the data.

      Now that we’ve established the groundwork, let’s move on to the pillars that support OOPs. First, though, let’s get familiar with what makes an Object-Oriented Language unique.

      What is the definition of the OOPs concept?

      The core of Java Programming is object-oriented programming, which is used to create a program’s structure with the help of objects and classes. OOPs, in a broader sense, can be understood as a means of restricting data access within a program. This method requires the programmer to specify both the data type of the data structure and the actions that can be performed on it.

      OOPs in Java: what is it?

      The goal of object-oriented programming, or OOps, in Java is to define a Java program effectively, hence enhancing the readability and reusability of the code. Abstraction, encapsulation, inheritance, and polymorphism are central to object-oriented programming. These principles are meant to be used while coding software that interacts with the real environment.

      OOPs Concepts in Java

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

      Objects

      In Java or any other language, objects that are constructed from a class are known as instances of the class. They exhibit states and actions. 

      These objects are always representations of things in the real world. Hence, they are addressed as “world entities” during runtime. These are self-contained, and they have the methods and properties that give data value. Physical and digital information both exist as “objects.” It uses some RAM and holds a list of addresses. Dogs, chairs, trees, etc. are instances of objects.

      Animals have attributes like color, name, breed, etc., as well as actions like feeding and swinging their tails when we consider them to be objects. Assuming that we have established a class named My book, we supply the class name, followed by the object name, and we employ the keyword new.

      Object Illustration :​
      1
      2
      3
      4
      5
      6
      7
      Public class Mynote
      {
      int x=12;
      Public static void main (String args [])
      {
      Mybook Myobj= new Mynote ();
      System.out.println(MyObj.x);
      }
      }

      A new object is formed and then returns a value, x in this case, which may be the total number of notes.

      Mynote Myobj= new Mynote ();

      Objects are created with this statement.

      System.out.println(Myobj.x);

      This statement can be used to retrieve an object’s x value.

      Furthermore, we can create numerous objects of the same class, as well as create in one class and then use that creation in another. This technique is utilized to better organize classes, and it is important to keep in mind that the name of the java file and the class name are exactly the same.

      Illustration 2 :

      This illustration exhibits how multiple objects are constructed in the same class and how they could be accessed via another class.
      Mynote.java

      1
      2
      3
      4
       
      Public class Mynote {

      int x=7;

      int y=11;

      }

      Count.java

      1
      2
      3
      4
      5
      6
      7
      8
      9
         
      Class Count {

      Public static void main (String [] args)

      {

      Mynote myobj1 = new myobj1();

                Mynote myobj2 = new myobj2();

                 System.out.println (myobj1.x);

      System.out.println (myobj2.y);

      }

      }

      On compiling this program, it shows the result as 7, and 11 respectively.

      Classes

      Classes can be thought of as analogs to object constructors because of their role in the object-creation process. A class is an organized grouping of items. The quantity of a class is said to be a logical one. There is no memory overhead associated with storing classes. Class is synonymous with object template. Fields, methods, and constructors are all examples of class members. There are two types of initializers for a class: static and instance. Learning a Java course in Chennai gives you insight into Java and OOPS concepts.

      The elements of a class declaration are :

      • Access to modifiers can be set to either public or default.
      • The initial letter is the name of this class.
      • The term “superclass” refers to the fact that a class can only extend (subclass) one of its parents.
      • The same class is able to implement multiple interfaces.
      • Braces encircling the body indicate the “body”
      • To make a new class, you’ll need to utilize the class keyword. 
      What follows is a streamlined explanation of the class description in its most basic form:

      class classname {

      type instance variable 1;

      type instance variable 2;

      .

      .

      .

      type instance variable n;

      type methodname 1 (parameter list) {

      // body od method

      }

      type methodname 2 (parameter list) {

      // body od method

      }

      type methodnamen (parameter list) {

      // body od method

      }

       }

      Instance variables are the informational variables or data stored within a class. Methods are the primary locations for coding. Therefore, a class’s variables and methods are referred to as “members.” None of the methods are marked as static or public, but they all share the same format as the main ().

      Abstraction

      Abstraction is a method that reveals only the essential details while concealing the rest. The primary goal of abstraction is to conceal information. To abstract means to pick data from a huge quantity of data to provide the information needed, which helps to reduce programming complexity and effort.

      In addition, there are abstract methods and abstract classes. When one or more abstract methods are declared, the class is said to be abstract. A method that is only defined but not implemented is said to be abstract. Once we’ve modeled our object using data abstraction, we can reuse the same sets of data in many contexts, such as abstract classes, generic types of behaviors, and the object-oriented programming hierarchy. When multiple subclasses do the same operation in different ways and with distinct implementations, an abstract method should be utilized. There can be both abstract methods and normal methods in an abstract class.

      Let’s look at an illustration of abstraction right now. Let’s say we want to build a student app that requires personal data collection. We tend to collect the below information/data for the student app.

      • Name of student
      • Classes
      • Residential Address
      • Date of birth
      • Father’s name
      • Mother’s name and so on.

      It’s possible that not all of the data we’ve gathered will be necessary. We therefore just provide the requested information in the application. As a result, we have extracted the student data from massive datasets, cleaned them, and chosen the most relevant information. In the oops theory, we refer to this action as an abstraction. Enroll in the best Java training in Chennai and emerge successful.

      Abstract class Illustration :

       

      1

       

      2

       

      3

       

      4

       

      5

       

      6

       

      7

       

      8

       

      9

       

      10

       

      11

       

      12

       

      13

       

      14

       

         

       

      //abstract parent class

       

              Abstract class bird {

       

               //abstract method

       

            public abstract void colour ( ) ;

       

               }

       

           Public class parrot extends colour {

       

            Public void colour ( ) {

       

      System.out.println (“ green “ );

       

      }

       

      public Static void main ( String args [ ] ) {

       

       bird obj = new parrot ( );

       

      obj. colour ();

       

      }

       

      }

       

      Output: 

       

      Green

      Inheritance

      Inheritance is a technique wherein an object takes on the characteristics of another, and it also facilitates the organization of data into hierarchical structures. The notion is that by creating new classes that inherit from existing classes, we may take advantage of the parent class’s already-existing functionality without having to write it all over again. The inheritance process is symbolic of the bond between parents and their offspring. Check out our Java course in Chennai if you want to learn more about this idea.

      A whale, for instance, belongs to the category of marine animals, which is subclassed under the class of mammals. Our system employs a hierarchical, or top-down, approach to categorizing data. Specific characteristics, like as whether an animal is cold-blooded or warm-blooded, or whether it has teeth, are used to classify specific groups of species, such as mammals. Comparatively, animals constitute the superclass, with this falling under the subclass of animals. The subclass is a type of class that takes some characteristics from the superclass as its own. The term “derived class” can be used interchangeably here. The attributes of a subclass are inherited from its superclass parent.

      Method overriding is the primary use case for an inheritance, and R:

      The extend keyword is utilized to inherit a class.

      • Single inheritance, 
      • Multi-level inheritance, 
      • Multiple inheritances at different levels, 
      • Hybrid inheritance, and 
      • Hierarchical inheritance are the five types of inheritance.

      Become successful in your career by joining Java training in Chennai.

      Single-level Inheritance

      In this singular instance, the derived class actually do inherit properties from its parent class. Because of this, the code may be reused, and new features can be added to it. To illustrate, let’s say that Class B inherits some of Class A’s features.

      Class B is the offspring of Class A, the “parental” class.

      Syntax :

       

      1

       

      2

       

      3

       

      4

       

      5

       

      6

       

         

       

      Class a {

       

       

      }

       

      Class b extends class a {

       

       

      }

      Multilevel

      Class X is derived from Class Y, which is derived from Class Z, and so on; this class has multiple parents and is thus said to exhibit multilevel inheritance.

      Syntax

      1

      2

      3

      4

      5

      6

      7

      8

      9

         

      Class a {

      ….

      }

      Class b extends class a {

      ….

      }

      Class c extends class b {


      }

      Hierarchical Inheritance

      In this case, there is a single parent class that is the parent of multiple offspring classes.

      Syntax :

      1

      2

      3

      4

      5

      6

      7

      8

      9

         

      Class a {


      }  

      Class b extends class a {

      ..

      }

      Class c extends class a {

      ..

      }

      Hybrid Inheritance

      This is a combination of multiple and multilevel inheritances; however, multiple inheritances are not permitted in Java due to the ambiguity they introduce, therefore multilevel inheritance in Java must be accomplished using interfaces.

      Keep in mind that Class a is the parent or base class of Classes b and c and that Classes b and c are the parents or base class of Class d. Class b and class c are considered to be derived classes from class a, but class d is considered to be a derived class from classes b and c.

      The following code generates two classes, add and sub, with the latter being a subclass of the former thanks to the use of the extend keyword.

      Syntax

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      12

      13

      14

      15

      16

      17

      18

      19

      20

         

      public class cars {


      Public void place of manufacture ( ) {

      System.out.println ( “ car place of manufacture “ );

      }

      }

      public class maruti extends cars {


      @override

      public void  ( ) {

      System.out.println( “  japan ” ) ;

      }

      }

      public class mahendra extends car ( ) {

      ….

      @override

      Public void sound ( ){

      System.out.println( “ india ” ) ;

      }

      }

      We observe that there are multiple ways to do the same action, represented by the common action () in the preceding example. A good illustration of polymorphism can be seen here.

      Java polymorphism can be broken down into two categories :

      • Static / Compile-Time Polymorphism
      • Dynamic / Runtime Polymorphism

      How does Java support polymorphism at compile time?

      Java’s Compile-Time Polymorphism, also called Static Polymorphism, allows for outstanding issues between classes to be addressed during compilation. This is accomplished via Method Overloading.

      To what extent does Java support polymorphism at runtime?

      Java’s runtime polymorphism, also known as Dynamic Binding, allows you to invoke an overridden method whose implementation is determined at runtime rather than compile time.

      Encapsulation

      Encapsulation is one of the Object-Oriented Programming (OOP) ideas. It is the procedure that binds together the code and data into a single unit and preserves both from being secured from being interfered with or misused by outside sources. When this happens, the information is protected from being accessed by other classes and is instead available only through the methods of the current class. Because of this secondary meaning, the term “data concealing” is also commonly used. Code and data are shielded from prying eyes by being encapsulated in an impenetrable layer of security. The interface for manipulating these is clear and straightforward.

      Declaring variables as private and offering public setter and getter methods to access and modify the variables’ values is how encapsulation is accomplished. Read-only or write-only fields are used in encapsulation to prevent unauthorized changes to data within a class. The approach also increases the method’s reusability. As a bonus, unit testing is less of a hassle when working with encapsulated code. To know how to implement Java OOPS concepts, join SLA for the top Java training in Chennai.

      class student {

      // private field

      private int location;

      //getter method

      Public int getlocation ( ) {

      return location;

      }

      //setter method

      public void setLocation ( int location ) {

      this. Location = location;

      }

      }

      class Main {

      public static void main (String args []);

      //create an object of person

      Student a1= new Student ();

      //change location using setter

      A1. setLocation (Chennai);

      // access location using getter

      System.out.println(“ Student location is ” + a1. getlocation ( ) );

      }

      }

      Output : Student location is Chennai

      In this case, we restricted access to a field within the class named location by declaring it private.

      We relied on open resources to determine ages. Getter and setter methods are the names for these operations. We can prevent students and teachers from being able to see their ages if we make this information private. We refer to this phenomenon as “data hiding” because of this reason. Emerge success in your profession by mastering Object-oriented programming concepts in Java by joining our SLA institute.

      Association

      The relationship between objects is defined by the concept of association in object-oriented programming and systems. The diversity of relationships between items is determined by the associations between them. Objects like a Teacher and a Student are one such example. The relationship between a teacher and their students is one of many to one. Similar to how a teacher can have a one-to-many relationship with student objects, the reverse is also true. However, the roles of students and teachers in the classroom are not interdependent.

       

      Aggregation

      In this context, “association” refers specifically to aggregation. It’s important to note that under aggregation, things still have their own distinct lifetimes and distinct owners. Aggregation occurs if there is a “HAS-A” relationship between items and ownership.

      Composition

      When it comes to aggregation, composition is a special situation. This composition represents a narrower type of aggregation. Composition occurs when the item in the “HAS-A” relationship within which it is contained cannot exist independently. In the case of the House, one of the rooms is called the Room. In this case, the room would be meaningless if the home didn’t exist. It has been argued that composition is preferable to inheritance.

      Potential Benefits of the OOPs Approach

      Several benefits include:

      Re-usability

      Re-usability refers to the ability to “write once, use it several times,” or to make use of a facility more than once without having to recreate it from scratch. It’s useful enough that we can reuse it n times.

      Data redundancy

      It’s a major perk of oops and one of the best features. When the same piece of information is stored in two different locations, this is the state that is formed at the data storage level. Inheriting common class definitions with similar functionality allows us to reuse the same code across several classes. Join the best Java training in Chennai at SLA to land on a high-paying job.

      Coding Upkeep

      Because new objects can be produced with only minor variations from the current ones, modifying or maintaining existing code is a breeze. This saves the user time and effort by allowing them to make adjustments to the already-existing programs rather than starting from scratch each time.

      Security

      With the use of data hiding and abstraction, we may restrict access to only the information that is truly necessary while keeping the system secure.

      Design advantages

      A longer and more thorough design phase means the designers have more time to think things through and come up with better solutions. In the event that the program reaches its boundaries, it will be simpler to code all non-oops independently.

      Troubleshooting is simple.

      Using objects that encapsulate data imposes their own limitations. Therefore, simple problems encountered by developers can be addressed. Moreover, there will be no room for code duplication.

      • Ability to Adapt and 
      • Solve Problems
      1
      Softlogic-Academy