Pages

Monday 15 August 2016

OOPS Concepts in Java

In this tutorial we will learn about the OOPS(Object Oriented Programming System)  Concepts.

Before moving into Object Oriented Programming Concepts we will understand the basic topics like Class and Object.


Object :

Object is a  Entity which has state and Behavior is a object.

Object has three characteristics
1. State
2. Behavior
3, Identity - JVM maintains one unique id internally for each Object.

   Example - Fan, Bike, Chair etc..

    Object can be both physical and logical.

Class:

 Class is a logical Entity , it is a collection of objects.

Real time example for Object and class  -

For Example take mobiles like  Samsung, IPHONE . They are the real world entities . They have state and the have behaviors like calling , sending message,playing games etc..

But these all mobiles will come under one Section that is Mobile(Class) . So, Mobile(Generic) is a collection of Different Mobile Brands.


What is difference between object-oriented programming language and object-based programming language?

Object based programming language follows all the features of OOPs except Inheritance. JavaScript and Vb-script are examples of object based programming languages.


Objected Oriented Concepts:

Encapsulation


Definition 
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. Its actually hiding the implementation details

The Java Bean class is the example of fully encapsulated class.

Encapsulation will give the ability to change your code without breaking anyone else code.

How to achieve encapsulation,
1. Keep instance variables protected (Private as Modifier)
2.  Make Methods public. So that developers can call the methods but cant access variables directly
3. For the methods use java bean naming convention like set<someProperty> and get<some
Property>


Please find the below diagram for clear understanding of Encapsulation





You can see in the above picture you can only access methods but cant access the variables directly.

So, what are you trying to achieve here by restricting the access?

In case in future if you want to change the method get Balance methods on some condition you can add your logic there and can return the value to the user.Say we can check the user requesting valid or not depending on that we will send the request back.

So, Encapsulation is Writing your code by hiding the implementation details in such a way that no can break your code in future.


Inheritance


Inheritance is everywhere in Java.Its safe to say almost.

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

By using Inheritance we can use the existing classes and can use there methods and variables in the child classes without actually creating object for it. There are two reasons to use Inheritance
1. Code Reuse
2. To use Polymorphism.

Understanding Inheritance:

Let's say there is a Buffalo Class which has behaviors (methods) like eating Grass, walking, sleeping and also properties like color.

Now there are other two classes WhiteBuffalo and BlackBuffalo. Even they have to eat grass(as all buffaloes have to eat grass :) ) , they have to walk on four legs and sleep. Only difference will be there property COLOR. So, instead of re writing the whole code again in the WhiteBuffalo and BlackBuffalo classes we will re use the code which is written in Buffalo.

We can achieve Interface using extends keyword.

Please look at the below classes code for moments and look at the explanation below :

public class Buffalo{
//some code here
public void eatGrass(){
System.out.println("Buffalo eating Grass"):
}
}

public class BlackBuffalo extends Buffalo{
//some code
eatGrass(); //calling eat grass method in parent class instaed of re wirting the code
}

Here BlackBuffalo Class just extends the Class Buffalo and it is just calling the method eatGrass() in its parent Class instead of writing it again.

There are two types of Inheritance. They are
1. IS-A Relationship (Composition)
2.HAS-A Relationship (Aggregation)



 


Please take a moment by looking at the below code and then description below the code for explanation.

Class Car{
//code for class car
}

Class Maruthi extends Car{
private Engine Engine;
//some code here
}

Class Engine{
//Some code for Engine Class
}

So, after seeing the above classes its very clear that
1. Maruthi  extends Car means Maruthi IS-A Car.
2. Maruthi having a property which refers to other Class Engine. Maruthi HAS-A Engine

Here Engine is not extending the Maruthi but inheritance exists.

Note: We will go for Aggregation(HAS-A) when there no are no parent-child relationship.

Polymorphism


Definition:

Polymorphism in java is a concept by which we can perform a single action by different ways. Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms.

Example: "+" is used for adding for adding two numbers but the same "+" is used for two string it will do concatination.

1+1 =2;
"Java"+"code"="Javacode";

Coming to java we will use polymorphism on objects.

Remember any Object that can pass one or more IS-A test can be considered polymorphic.

So,its easy to say all objects are polymorhic in Java. Because by default all objects extends Object Class. Any object by default is of its own type and also of Object type.

Example:

Please look at the following code then we will discuss about the code and how the ob ject is polymorphic in detail later:

Interface Vehicle{
//Code for vehicle
}

Class Car {
//code for car
}

Class Maruthi extends Car implements Vehicle{
//code for Maruthi
}

Now if we see the Maruthi Class the followiung points holds tru for that
1. Maruthi IS-A car (Inheritance as it uses extends)
2. Maruthi is also of type Vehicle (Class can extend only call so we made vehicle Interface)
3. Maruthi is of its own type
4. Maruthi is also an Object(By Default all classes extends Object Class)


So, Maruthi is Poymormic and the following declarations are legal look closely

Create a object for Maruthi Maruthi maruthi = new Maruthi();

Object o = maruthi;
Vehicle v = maruthi;
Car car = maruthi;


Overriding:

Anytime when the class extends its super class you have the ability to override the method in your child class(unless the method is marked final). Benifit of overriding is to define the behavior that specific to a particular subclass type.


Example for Overriding:
  public class Animal {
public void eat() {
System.out.println("Generic Animal Eating Generically");
}
}

class Horse extends Animal {
public void eat() {
System.out.println("Horse eating hay, oats, "+ "and horse treats");
}}

If we see in above example, Class Horse can re use the code of eat method of Animal as it extends the class Animal, but we override the method to provide our own implementation to the class Horse for eat method.

Overriding a method is optional but if the super class is of abstract type and having abstract methods then there is no choice you much override the methods. All abstract methods in abstract class must be overridden by the 1st concrete sub class .More details in Abstraction module.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.

Abstract Class:
        A Abstract Class should not be instantiated (should not create object), Its sole purpose should be extended.

So, why we want a Class when cant make objects of it?
 Imaging you have Class Car that has all generic properties like price,color and abstract methods like goSpeed(). Abstract method means its just a method without any implementation.

Example for Abstract method:
public abstract void goSpeed();

If you observe the above abstract method it has no implementation and it ends with semicolon.

So, now any new car comes .. we will create a car class like audi and it will extend the Car Class.
So, As we discussed earlier all the abstract methods in abstract class must be implemented by first concrete subclass of the abstract class. So, abstract class will have abstarct methods it means all the methods should be implemented by the subclass of the abstract class.

What if there are multiple Abstract classes we have to extend , but Class can extend only one?

As we know class can extend only one class, if we extend that class we are blocked we cant extend any other classes, this is the reason why we go for Interfaces.

Interface:

Interface in Java is completely abstract . By default all the methods in Interface will be abstract. A Class can implement any number of Interfaces.






No comments:

Post a Comment