Real Time example in Oops Concepts

Abstraction
Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it shows only important things to the user and hides the internal details.
Achieve Abstaction
There are two ways to achieve abstraction in java
1.    Abstract class (0 to 100%)
2.    Interface (100%)
Abstract class
A class that is declared as abstract is known as abstract class.It needs to be extended and its method implemented. It cannot be instantiated.
Example  :
abstract class A
{
// abstract methods
// some concrente methods
}
abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.
abstract return_type <method_name>();//no braces{}
Example :
abstract void test();
abstract int method (inti) ….. etc
It should be used abstract keyword
When to use ? :
At the time of implementing the Inheritance if you found few common and few specific state or methods or behavior in both parent and child class, You should use abstract parent class and your parent abstract class should contain:
Common methods (non-abstract) with non-private visibility so child class can access them.
Abstract methods which child class are suppose to implement as per requirement.
You can also put common state or behavior of Inheritance hierarchy classes here. 
Example
abstract class Bank {
    // common methods
    public int withdraw() {
        // method body
    }
    public boolean deposit() {
        // method body
    }
        // abstract methods
    public abstract void openAccount();
    public abstract void closeAccount();
}
classHSBCBank extends Bank {
    public void openAccount() {
        // method body
    }
    public void closeAccount() {
        // method body
    }
}

Interface The interface is a mechanism to achieve full abstraction in java. There can be only abstract methods in the interface. It is used to achieve fully abstraction and multiple inheritance in Java.
Example :
interface A
{
// some methods
// some body        
}
Use Interface :-
·         It is used to achieve fully abstraction.
·         By interface, we can support the functionality of multiple inheritance.
·         It can be used to achieve loose coupling.
Marker Interface : -
An interface that have no member is known as marker or tagged interface. For example: Serializable, Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation
At the time of implementing the Inheritance when there is no any common state or method or behavior and you want certain kind of contract to be implemented by child classes by overriding the methods you should use Interfaces. Your Interface should contain:
  1. Only abstract methods (behavior only - no state).
  2. Global constants.
Inheritance implementation with Abstract or Concrete class is called Generalization.
Inheritance implementation with Interface is calledRealization
interfaceRuleEngine {
    // by default variables are public static final only
    int RULE_CONSTANT = 1;
  
    // contract methods needs to be implemented by concrete classes.
    // by default declared methods are public abstract only.
    voidcreateRule();
    void updateRule();
    void deleteRule();
    public abstract void getAllRule();
}
classSalesRuleEngine implements RuleEngine {
    public void createRule() {
        // method body
    }
    public updateRule() {
        // method body
    }
    public void deleteRule() {
            // method body
    }
    public void getAllRule() {
        // method body
    }
}
Some important abstract classes in Java API are:
  1. AbstractList
  2. AbstractSet
  3. AbstractMap etc...
Some important Interfaces in Java API are:
  1. Serializable
  2. Clonnable
  3. List, Set, Map etc...
4.    Abstract classes and Interfaces are nearly similar with both having only method declarations and no implementations thereby giving their child classes the flexibility to implement them the way they want.
Difference: While an abstract class can have method implementations also, an interface can have only declarations.
All methods in an interface are only declared but in an abstract class you can declare as well as implement a few methods also.
polymorphism
The abiltiy to define more than one function with the same name is called Polymorphism. In java,c++ there are two type of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding).
When you override methods, JVM determines the proper methods to call at the program’s run time, not at the compile time. Overriding occurs when a class method has the same name and signature as a method in parent class.
Overloading occurs when several methods have same names with
  • Overloading is determined at the compile time.
  • Different method signature and different number or type of parameters.
  • Same method signature but different number of parameters.
  • Same method signature and same number of parameters but of different type
Real life example :
  class Bike{  
  void run(){System.out.println("running");}  
}  
class Splender extends Bike{  
  void run(){System.out.println("running safely with 60km");}  
  
  public static void main(String args[]){  
    Bike b = new Splender();//upcasting  
    b.run();  
  }  
}  

Real time example :
 class Bank{  
int getRateOfInterest(){return 0;}  
}  
  
class SBI extends Bank{  
int getRateOfInterest(){return 8;}  
}  
  
class ICICI extends Bank{  
int getRateOfInterest(){return 7;}  
}  
class AXIS extends Bank{  
int getRateOfInterest(){return 9;}  
}  
  
class Test3{  
public static void main(String args[]){  
Bank b1=new SBI();  
Bank b2=new ICICI();  
Bank b3=new AXIS();  
System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());  
System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());  
System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());  
}  
 
Encapsulation :
Encapsulation in java is a process of wrapping code and data together into a single unit, for example capsule i.e. mixed of several medicines. We can create a fully encapsulated class in java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it.
The Java Bean class is the example of fully encapsulated class.
Advantage of Encapsulation in java
By providing only setter or getter method, you can make the class read-only or write-only.
It provides you the control over the data. Suppose you want to set the value of id i.e. greater than 100 only, you can write the logic inside the setter method.
Simple example of encapsulation in java
Let's see the simple example of encapsulation that has only one field with its setter and getter methods.
1.    //save as Student.java  
2.    package com.javatpoint;  
3.    public class Student{  
4.    private String name;  
5.       
6.    public String getName(){  
7.    return name;  
8.    }  
9.    public void setName(String name){  
10. this.name=name  
11. }  
12. }  
1.    //save as Test.java  
2.    package com.javatpoint;  
3.    class Test{  
4.    public static void main(String[] args){  
5.    Student s=new Student();  
6.    s.setname("vijay");  
7.    System.out.println(s.getName());  
8.    }  
9.    }  

oops real time examples
ENCAPSULATION:
Wrapping up data and member functions in a single unit for easier and safer access.

INHERITANCE:

A new class(child) can be based on existing class(parent) deriving functionallity from parent class.

Polymorphisam: An Object is in different forms and in each form its exhibit the same functionality but the implementation is different.

Eg: A Person who knows more than two languages he can speak in a language which he knows. Here person is Object and speak is polymorphism.
Inheritance: The process of eqiring the existing functionality of parent and with new added features and functionality of a child Object.
A secintific calculator is a extend form of Caluculator here Caluculator is parent and secintific calculator is Child object.
Encapsulation: Binding of data and behavior i.e functionality of an object in a secured and controlled manner.
POLYMORPHISM-
poly means "MANY" ,
orphism  means "FORMS"..
MEANS many forms
or u can say that a object(person, place or thing) acts differently in different situations
example-
if a girl is married and mother of 2 children doing teaching job den
she is a women first ,, teacher in a school whn she is in school,,wife of someone at home,, mother of her children,, and obvious daughter of someone & may be girl friend of someone (just kidding) means a woman plays diffent roles at different times dats the polymorphism (many forms)
now overloading is achivd in c# by two ways a)method overloading also called compile time polymorphism
b)method overriding  also known as run time polymorphism.
======================
inheritence= means to inherit(adopt) the feature/functionality of base class and also add their own functionality..
EXMPLE- a child inherit(adopt) some features of their parents & also add some features of their own
ENCAPSULATION-means hide/bind something ex- a capsule (which we consume whn v r ill)hide/bind some powder form in itself,, means that capsule encapsulate the powder contained it.
or the best example of encapsulation is a CLASS becoz a class hides class variables/functions from outside d class.. 
 Difference between Abstraction and interface :
Abstraction
Encapsulation
1. Abstraction solves the problem in the design level.
1. Encapsulation solves the problem in the implementation level.
2. Abstraction is used for hiding the unwanted data and giving relevant data.
2. Encapsulation means hiding the code and data into a single unit to protect the data from outside world.

3. Abstraction lets you focus on what the object does instead of how it does it
3. Encapsulation means hiding the internal details or mechanics of how an object does something.
4. Abstraction- Outer layout, used in terms of design.
For Example:-
 Outer Look of a Mobile Phone, like it has a display screen and keypad buttons to dial a number.
4. Encapsulation- Inner layout, used in terms of implementation.
For Example:- Inner Implementation detail of a Mobile Phone, how keypad button and Display Screen are connect with each other using circuits.

OOPs interface vs abstract class

Interface
Abstract class
Interface support multiple inheritance
Abstract class does not support multiple inheritance
Interface doesn't Contains Data Member
Abstract class contains Data Member
Interface doesn't contains Constructors
Abstract class contains Constructors
An interface Contains only incomplete member (signature of member)
An abstract class Contains both incomplete (abstract) and complete member
An interface cannot have access modifiers by default everything is assumed as public
An abstract class can contain access modifiers for the subs, functions, properties
Member of interface can not be Static
Only Complete Member of abstract class can be Static

Difference between String and String Buffer and String Builder
String

String is immutable  ( once created can not be changed )object  . The object created as a String is stored in the  Constant String Pool  .
Every immutable object in Java is thread safe ,that implies String is also thread safe . String can not be used by two threads simultaneously.
String  once assigned can not be changed .

String  demo = " hello " ;
// The above object is stored in constant string pool and its value can not be modified.


demo="Bye" ;     //new "Bye" string is created in constant pool and referenced by the demo variable           
 // "hello" string still exists in string constant pool and its value is not overrided but we lost reference to the  "hello"string 

StringBuffer

StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap .  StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe .

Due to this it does not allow  two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .

But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property . Thus  StringBuilder is faster than the StringBuffer when calling the same methods of each class.

StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes .
String Buffer can be converted to the string by using
toString() method.

StringBuffer demo1 = new StringBuffer("Hello") ;
// The above object stored in heap and its value can be changed .
demo1=new StringBuffer("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuffer
StringBuilder
StringBuilder  is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe. 
StringBuilder is fast as it is not thread safe . 
StringBuilder demo2= new StringBuilder("Hello");
// The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuilder
----------------------------------------------------------------------------------
                                    String                    StringBuffer         StringBuilder
----------------------------------------------------------------------------------                
Storage Area | Constant String Pool           Heap                       Heap
Modifiable     |  No (immutable)            Yes( mutable )          Yes( mutable )
Thread Safe   |           Yes                                  Yes                              No
 Performance |         Fast                                Very slow                    Fast
-----------------------------------------------------------------------------------
Examples
public class Main {
    public static void main(String[] args) {
        int N = 77777777;
        long t;

        {
            StringBuffer sb = new StringBuffer();
            t = System.currentTimeMillis();
            for (int i = N; i --> 0 ;) {
                sb.append("");
            }
            System.out.println(System.currentTimeMillis() - t);
        }

        {
            StringBuilder sb = new StringBuilder();
            t = System.currentTimeMillis();
            for (int i = N; i --> 0 ;) {
                sb.append("");
            }
            System.out.println(System.currentTimeMillis() - t);
        }
    }
}
Immutable Class :
Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
Let's try to understand the immutability concept by the example given below:
class Testimmutablestring{  
 public static void main(String args[]){  
   String s="Sachin";  
   s.concat(" Tendulkar");//concat() method appends the string at the end  
   System.out.println(s);//will print Sachin because strings are immutable objects  
 }  
}  

How to write immutable class in Java

Despite of few disadvantages, Immutable object still offers several benefits in multi-threaded programming and it’s a great choice to achieve thread safety in Java code. here are few rules, which helps to make a class immutable in Java :

1. State of immutable object cannot be modified after construction, any modification should result in new immutable object.
2. All fields of Immutable class should be final.
3. Object must be properly constructed i.e. object reference must not leak during construction process.
4. Object should be final in order to restrict sub-class for altering immutability of parent class.

Example :
public final class Contacts {

    private final String name;
    private final String mobile;

    public Contacts(String name, String mobile) {
        this.name = name;
        this. mobile = mobile;
    }                                                                                                                       
  
    public String get Name(){
        return name;
    }
  
    public String get Mobile(){
        return mobile;
    }
}
                                 

Serialization in Java
Serialization is the process of converting an object's state (including its references) to a sequence of bytes, as well as the process of rebuilding those bytes into a live object at some future time. Simple......Coverting an object to bytes and bytes back to object. So when is serialization used? Serialization is used when you want to persist the object. It is also used by RMI to pass objects between JVMs, either as arguments in a method invocation from a client to a server or as return values from a method invocation. In general, serialization is used when we want the object to exist beyond the lifetime of the JVM.
Lets see couple of different scenarios (examples) where we use serialization.
·         1. Banking example: When the account holder tries to withdraw money from the server through ATM, the account holder information along with the withdrawl details will be serialized (marshalled/flattened to bytes) and sent to server where the details are deserialized (unmarshalled/rebuilt the bytes)and used to perform operations. This will reduce the network calls as we are serializing the whole object and sending to server and further request for information from client is not needed by the server.
·         2. Stock example: Lets say an user wants the stock updates immediately when he request for it. To achieve this, everytime we have an update, we can serialize it and save it in a file. When user requests the information, deserialize it from file and provide the information. This way we dont need to make the user wait for the information until we hit the database, perform computations and get the result.
Here are some uses of serialization
·         To persist data for future use.
·         To send data to a remote computer using such client/server Java technologies as RMI or socket programming.
·         To "flatten" an object into array of bytes in memory.
·         To exchange data between applets and servlets.
·         To store user session in Web applications.
·         To activate/passivate enterprise java beans.
·         To send objects between the servers in a cluster.

Example :
    
import java.io.*;
class Employee implements Serializable
{
public int eno;
public String ename;
public double sal;
}
class WriteSObject
{
 public static void main(String args[]) throws Exception
 {
 Employee e=new Employee();
 e.eno=1;
 e.ename="Gowtham Gutha";
 e.sal=200000.95;

 FileOutputStream fout=new FileOutputStream("out.dat");
 ObjectOutputStream out=new ObjectOutputStream(fout);

 out.writeObject(e);

 out.close();
 fout.close();
 }

}

No comments:

Post a Comment