OOPs Concepts

 

(5) OOPS CONCEPTS :-  

Object-oriented programming – As the name suggests uses objects in programming.
It aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming.

The main 
aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.





5.1) CLASSES IN OOPS CONCEPTS:-
class is a group of objects which have common properties and have ability of blue-printing for objects creation.

Blue-print or template(CARBON PAPER)
It representing a 
group of objects that shares common properties and behaviours.
(CARBON-PAPER draw objects like tracing a drawing with same properties and behaviours)

Example: Consider the class of Cars.
There are many cars with 
different names and brand with same properties like:-
having 4 wheels, Speed Limit, Mileage range etc.
So, 
Cars is the class with wheels, speed limits, mileage as their properties.

  • A Class is a user-defined data-type that has data members & member functions.
  • Class can contain only one PUBLIC Class in a program.
  • A Class creation can be possible without even taking space in memory.
  • Data members are the data variables and member functions are the functions used to manipulate these variables & together they define the properties and behaviour of the objects in a Class.
  • In the above example of class Cars, the data member will be speed limit, mileage etc and member functions (methods) can apply brakes, increase speed etc.
5.2) OBJECTS IN OOPS CONCEPTS:-

When a program is executed the objects interact by sending messages to one another.
We can define an object in terms of its properties (attributes),
behaviour (methods), and interfaces (means of communicating with other objects).


Each object contains data and code to manipulate the data. Objects can interact without having to know details of each other’s data or code, it is sufficient to know the type of message accepted and type of response returned by the objects.

  • OBJECTS have some state & behaviour.
  • Objects are known as instance of a class.
     [e.g Class obj = new Class();]
  • Objects can hold address & space in memory.

    5.3 & 5.4  DATA HIDING


    5.3) 
    ENCAPSULATION IN OOPS CONCEPTS:- 
    (Private variables, Public Getter/Setter & GO!)

In JAVA it's a process of WRAPPING CODE & DATA of similar group together into a single unit.
example:- PACKAGE structure in JAVA

Encapsulation also leads to data abstraction or hiding.
Encapsulation also helps in hiding the data.


5.3.0 HOW TO ACHEIVE ENCAPSULATION?

STEP 1:- Declare Variable as private.
STEP 2:- Provide public Getter/Setter.
                (To write & read this variable values, Source-generate getter/setter)
STEP 3:- GO! Now, Get ready to operate this same group of data from outsides.


->Setter me condition laga sakte hai.
(Control modificationex:-money < 5000  = 0)
->public getter & public setter helps in restricted data access in java.


5.3.1 ADVANTAGES of encapsulation:-

  • Keep related fields & methods together.
    example:- java.lang package classes.
  • Makes code Cleaner & Easy to Read, Modify.
  • Helps to decoupled(separate) the component-system.
    (Decoupled components can be developed, tested & debugged independently)
  • Concurrently any change in a particular component don't effect over other components in program.

5.4) ABSTRACTION IN OOPS CONCEPTS:- 

The process of reducing the object to its essence such that only the necessary characteristics are exposed to the end-users.

Abstraction means displaying only essential information and hiding the details.
example:- Race in Bikes, Acceleration in Cars.   


Example 5.4
:-   
An Owner is interested in details like Car description, service history, etc


Garage Persons are interested in details like License, work description, bill, owner, etc;

Registration Office interested in details like vehicle identification number, current owner, license plate, etc.

HERE:- ABSTRACTION PROVIDES EXTERNAL VIEW TO THE ENTITY.


ABSTRACTION can refer as way of filtering out the unnecessary details of an object. so, that there remain only the useful characteristics that define it.


5.4.0 How to Achieve Abstraction in Java?

 
By using Abstract classes and Interfaces(Interface have NO concrete method)
  A class can extend only one abstract class while a class can implement multiple                interfaces.
  • Complete Abstraction:- Interfaces allow to abstract the implementation completely. Such, that 100% abstraction can be achieved as a result.
    (Interface methods are by definition public and abstract, so, we cannot have non-abstract methods in our interface.)

  •  Partial Abstraction:- Since Abstract classes can contain concrete methods that have complete implementation is resulting in partial abstraction.
    Abstract classes allow 0 to 100% abstraction (partial to complete abstraction).

5.4.1 ABSTRACT METHOD & 5.4.2 ABSTRACT CLASSES:-

-> Abstract variable is not valid.
-> Object creation (Instantiation) is not possible. 

  • The interface has only static and final variables.
    Implementation:- Abstract class can provide the implementation of the interface.

  • We can declare fields, Variables that are static and not final in an abstract class


  • However, We can have static concrete methods.
    Reason:-
    Static methods don't allow to create the instance of class, 
    they are directly associated with the class itself.

  • We can define public, protected, and private concrete methods,
    A
    abstract method can only set a visibility modifier & cannot add static or final modifier to the declaration.

 5.4.1  Abstract Methods in Java

  • An abstract method is declared with an abstract keyword with  no implementation but only declaration.
  • An abstract method can only set a visibility modifier, one of public or protected. That is, an abstract method cannot add static or final modifier to the declaration.
  • The declaration of an abstract method must end with a semicolon ;
    NOTE:- not with { } as they do not have
     method statement/Implementation.
  • The child classes which inherit the abstract class must provide the implementation of these inherited abstract methods. (5.4.1.3)

ex- public abstract method();

5.4.1.1) If a class contains at least one abstract method, class must be declared as abstract.
5.4.1.2) If a method is not initialised, Class must be declare as abstract ;
5.4.1.3) Child class (Scooter) is responsible for all abstract method implementation.
Mandatory to declare all abstract method implementation.

Example :- 5.4.1,2
package com.car;

public abstract class Car

         public void speed() { }
         public abstract void speedHigh (); //Partial Implementation

}

/////////////////////////////////////////////////////////////////////////////MAIN CLASS////////////////////////////////////////////////

import com.car.Car;

public class Main {

public static void main(String[] args)

{          Example :- 5.4.1.3
                    class Scooter extends Car {

@Override
                             public void speedHigh()
                                       {
                                              System.out.println("Full power");
                                        }

@Override
                          public void speed()
                                      {
                                          System.out.println("Awesome");

                                       } 
                                                                    }

Scooter sc = new Scooter();
                             sc.speedHigh();

Scooter bk = new Scooter();
                              bk.speed();
}}

                                                     

5.4.2 Abstract Classes in Java:-

5.4.2 Abstract Class :- Partially implemented class...  Object creation (Instantiation) is not possible.

  • An Abstract class is a class whose objects can’t be created. An Abstract class is created through the use of the abstract keyword. 

  • An abstract class can have abstract methods (methods without body) as well as non-abstract methods or concrete methods (methods with the body).
    (A 
    non-abstract class cannot have abstract methods.)

  • Class has to be declared as abstract if it contains even one abstract method.

  • An abstract class does not allow you to create objects of its type.
    (In this case, we can 
    only use the objects of its subclass/child.)

  • Using an abstract class, we can achieve 0 to 100% abstraction.

  • Always a default constructor in an abstract class.
    (It can also 
    have parameterized constructor.)

  • The abstract class can also contain final and static concrete methods.



5.4.2.1) If the implementation of class is not proper and even if there is NO abstract method,
             we can still declare it as Abstract Class.
5.4.2.2) Abstract class can contains 0 abstract method also.
5.4.2.3) Just to provide mandatory implementation for every child class, we declare abstract classes.


Example :- 5.4.2,2  //This types of classes are called Adapter Class
abstract class Test
{
        public void m1() {
                                       //NO implementation 
                                      //VOID body

                                     } 

}                               

Example :- 5.4.2.3

class Exam extends Test
{

         public void m1() { 
                                           S.O.T(hi, This is your exam.);
                                          }


///////////////////////////////////////////////////////////////////MAIN CLASS////////////////////////////////////////////////////////
Exam ex = new Exam();

ex.m1();

Types of Abstraction in Java

1. Data abstraction

Data abstraction is the most common type of abstraction in which we create complex data types such as HashMap or HashSet, and hide its implementation details from the users and display only the meaningful operations to interact with the data type.

The benefit of this approach solves the performance issues and improves the implementation over time. Any changes which occur while improving the performance, do not reflect on the code present on the client-side.

2. Control abstraction

Control abstraction is the process of determining all such statements which are similar and repeat over many times and expose them as a single unit of work. We normally use this type of abstraction is when we want to create a function to perform any given task.

Advantages of Abstraction in Java

  • It reduces the complexity of viewing things.
  • Increases software reuse and avoids code duplication:
    Loosely-coupled classes often prove useful in other contexts.
  • It helps to increase the security and confidentiality of an application as only necessary details are exposed to the user.
  • Eases the burden of maintenance – Classes can be understood more quickly and debugged with little fear of harming other modules.

Data Encapsulation vs Data Abstraction in Java

  • Encapsulation is one step beyond abstraction.
  • Data Encapsulation is hiding data or information while Abstraction is hiding the implementation details.

  • Encapsulation binds the data members and methods together while data abstraction deals with showing the external details of an entity to the user and hiding the details of its implementation.
  • Abstraction provides access to a specific part of data while encapsulation hides the data.

Things to Remember
  • In Java, you can not create an object from the abstract class (compilation error).
  • An abstract class can have a constructor.
  • It can contain both abstract as well as concrete methods.
    An abstract method just has the declaration but not any method body.(meth();)
  • We can not declare a variable as abstract.
  • We use the keyword abstract to declare both class and method as abstract.
  • If we declare any method as abstract, the class automatically needs to become an abstract class.

    5.5 & 5.6 CODE REUSABILITY:-


    5.5) INHERITANCE IN OOPS CONCEPTS:- 


    Ability of an object that acquires all the properties and behaviours of parent object. Inheritance represents IS-A relationship :  also known as a  parent-child  relationship.

    5.5.1 Why use inheritance in java?

    5.5.2 The syntax of Java Inheritance 

    1. class Subclass-name extends Superclass-name  
    2. {  
    3.    //methods and fields  
    4. }  

    • Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.
    • Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.

    (5.5.3) Java Inheritance Example:-                                                                           

     Programmer is the subclass and Employee is the superclass. As Programmer IS-A Employee.

    1. class Employee{  
    2.  float salary=40000;  
    3. }  
    4. class Programmer extends Employee{  
    5.  int bonus=10000;  
    6.  public static void main(String args[]){  
    7.    Programmer p=new Programmer();  
    8.    System.out.println("Programmer salary is:"+p.salary);  
    9.    System.out.println("Bonus of Programmer is:"+p.bonus);  
    10. }  
    11. }  

    Programmer object can access the field of own class as well as of Employee class i.e. code reusability.

    (5.5.4) Types of inheritance in java:-

    Three types of inheritance on the basis of class:

    single, multilevel and hierarchical

    Note: Multiple inheritance is not supported in Java through class
              Multiple and hybrid inheritance is supported through interface only.

    5.5.4.1 Single Inheritance Example:-

    Dog class inherits the Animal class, so there is the single inheritance.

    1. class Animal{  
    2. void eat(){System.out.println("eating...");}  
    3. }  

    1. class Dog extends Animal{  
    2. void bark(){System.out.println("barking...");}  
    3. }  

    1. class TestInheritance{  
    2. public static void main(String args[]){  
    3. Dog d=new Dog();  
    4. d.bark();  
    5. d.eat();  
    6. }}  

    5.5.4.2 Multilevel Inheritance Example

    When there is a chain of inheritance, it is known as multilevel inheritance.
    BabyDog class inherits the Dog class which again inherits
    the Animal class, so there is a multilevel inheritance.

    1. class Animal{  
    2. void eat(){System.out.println("eating...");}  
    3. }  
    1. class Dog extends Animal{  
    2. void bark(){System.out.println("barking...");}  
    3. }  
    1. class BabyDog extends Dog{  
    2. void weep(){System.out.println("weeping...");}  
    3. }  

    1. class MultiLevelInheritance2{  
    2. public static void main(String args[]){  
    3. BabyDog d=new BabyDog();  
    4. d.weep();  
    5. d.bark();  
    6. d.eat();  
    7. }}  

    5.5.4.3 Hierarchical Inheritance Example:-

    When two or more classes inherits a single class, it is known as hierarchical inheritance.
    In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.

    1. class Animal{  
    2. void eat(){System.out.println("eating...");}  
    3. }  

    1. class Dog extends Animal{  
    2. void bark(){System.out.println("barking...");}  
    3. }  

    1. class Cat extends Animal{  
    2. void meow(){System.out.println("meowing...");}  
    3. }  

    1. class TestInheritance3{  
    2. public static void main(String args[]){  
    3. Cat c=new Cat();  
    4. c.meow();  
    5. c.eat();  
    6. //c.bark();    //C.T.Error  
    7. }}  


    Q) Why multiple inheritance is not supported in java?

    To reduce the complexity and simplify the language, multiple inheritance is not supported in java. (DIAMOND CHAIN PROBLEM).

    • Consider a scenario where A, B, and C are three classes.
    • The C class inherits A and B classes. If A and B classes have the same method and we call it from child class object, there will be ambiguity to call the method of A or B class.

    Java renders compile-time error if you inherit 2 classes.
    So, whether you have 
    same method or different, there will be compile time error.

    1. class A{  
    2. void msg(){ System.out.println("Hello"); }  
    3. }  
    4. class B{  
    5. void msg(){ System.out.println("Welcome"); }  
    6. }  
    7. class C extends A,B{//suppose if it were  
    8.  public static void main(String args[]){  
    9.    C obj=new C();  
    10.    obj.msg();//Now which msg() method would be invoked?  
    11. }  }  

    5.5.4.4 Multiple Inheritance:-
    When one class inherits multiple classes called Multiple Inheritance.



    https://www.javatpoint.com/aggregation-in-java

    5.5.6 Aggregation in Java

    If a class have an entity reference, it is known as Aggregation.
    Aggregation represents HAS-A relationship.

    1. class Employee{  
    2. int id;  
    3. String name;  
    4. Address address;//Address is a class, Employee HAS-A address.
    5. ...  
    6. }  

    1. class Operation{  
    2.  int square(int n){  
    3.   return n*n;  
    4.  }  
    5. }  

    6. class Circle{  
    7.  Operation op;//aggregation  
    8.  double pi=3.14;    
    9.  double area(int radius){  
    10.    op=new Operation();  
    11.    int rsquare=op.square(radius);
         //code reusability (i.e. delegates the method call).  
    12.    return pi*rsquare;  
    13.  }  

    14.  public static void main(String args[]){  
    15.    Circle c=new Circle();  
    16.    double result=c.area(5);  
    17.    System.out.println(result);  
    18.  }  
    19. }  

    When use Aggregation?

    • Code reuse is also best achieved by aggregation when there is no is-a relationship.
    • Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the objects involved; otherwise, aggregation is the best choice.

    5.5.7 POLYMORPHISM in JAVA:-

    Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways. (One name many different way.)

    superclass called Animal that has a method called animalSound(). Subclasses of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own implementation of an animal sound (the pig oinks, and the cat meows, etc.)

    class Animal {
      public void animalSound() {
        System.out.println("The animal makes a sound");
      }
    }
    
    class Pig extends Animal {
      public void animalSound() {
        System.out.println("The pig says: wee wee");
      }
    }
    
    class Dog extends Animal {
      public void animalSound() {
        System.out.println("The dog says: bow wow");
      }
    }

    5.5.7.1 TYPES POLYMORPHISM in JAVA:-

    (1) RUN time polymorphism / Dynamic polymorphism @Overriding
    (2) Compile time polymorphism /Static polymorphism @Overloading

    Comments